1

Can any one take a look at my simple directive and figure out why the transclude is not working?

html:

<div ng-app="app">
<div ng-controller="MainController">
    <p>Your name</p><input ng-model="name"></input><button ng-click="greeting()">click</button>
    <greeter nationality="English" name="{{name}}">Hahahahah</greeter>
    <greeter nationality="French" name="{{name}}">Hahahahah</greeter>
    <greeter nationality="Russian" name="{{name}}">Hahahahah</greeter>
</div>    
</div>

js:

var app = angular.module("app", []);



app.controller("MainController", function($scope) {

});

app.directive("greeter", function() {
  return {
    restrict: "AE",
    scope: {
      name: "@",
      nationality: "@"
    },
    transclude: true,
    template: "<div style='display:block'>{{name}}<div ng-transclude></div></div>",
    link: function(scope, elem, attr, ctrl) {
      scope.$watch("name", function() {
        elem.html(greeting + " " + scope.name);
      });
      var greeting = "";
      if (scope.nationality === "English") {
        greeting = "Hello";
      }
      else if (scope.nationality === "French") {
        greeting = "Bonjour";
      }
      else {
        greeting = "Howdy";
      }
    }
  };
});

1 Answer 1

1

You are overwriting the transcluded content when you insert the greeting text with elem.html(...).

Rather than manipulate the DOM with jqLite, you can include the greeting text directly in your template. For this to work, greeting must be a scope property (scope.greeting instead of var greeting).

template: "<div style='display:block'>{{greeting}} {{name}}<div ng-transclude></div></div>",
link: function(scope, elem, attr) {
  if (scope.nationality === "English") {
    scope.greeting = "Hello";
  } else if (scope.nationality === "French") {
    scope.greeting = "Bonjour";
  } else {
    scope.greeting = "Howdy";
  }
}

If you want to try the code for yourself, here it is on Plunkr.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.