Reputation: 93
So I am following this EggHead.io tutorial on custom components, and I came across this problem. When declaring a directive such as:
angular.module('myApp', [])
.directive('myDir', function(){
return {
restrict: "E",
controller: "myController",
link: function(scope, element, attrs) {
scope.foo = element.text();
},
templateUrl: "myDirTemplate.html"
}
});
and the Template being:
<div>The value is: {{foo}}</div>
and the directive being used such as follows:
<html>
...
<myDir>Bar</myDir>
...
</html>
element in the link function refers to the
<div>The value is: {{foo}}</div>
in the template. If I don't specify the templateUrl, then element refers to the
<myDir>Bar</myDir>
in the main view, which is what I want. I was hoping the directive would take the "Bar" text and insert it into the {{foo}}, giving the final result of:
<div>The value is: Bar</div>
But I don't know how to get around angular selecting the template's element every single time.
Any ideas?
Upvotes: 9
Views: 10248
Reputation: 19857
You need to use ngTransclude:
app.directive('myDir', function(){
return {
restrict: "E",
transclude: true,
templateUrl: "myDirTemplate.html",
replace: true
}
});
and then your external template becomes something similar to:
<div>The value is: <span ng-transclude></span></div>
View the code working here: http://plnkr.co/edit/EuT5UlgyxgM8d54pTpOr?p=preview
Upvotes: 22