Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  153] [ 1]  / answers: 1 / hits: 152962  / 11 Years ago, tue, november 19, 2013, 12:00:00

I've tried to write a small directive, to wrap its contents with another template file.



This code:



<layout name=Default>My cool content</layout>


Should have this output:



<div class=layoutDefault>My cool content</div>


Because the layout Default has this code:



<div class=layoutDefault>{{content}}</div>


Here the code of the directive:



app.directive('layout', function($http, $compile){
return {
restrict: 'E',
link: function(scope, element, attributes) {
var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
$http.get(scope.constants.pathLayouts + layoutName + '.html')
.success(function(layout){
var regexp = /^([sS]*?){{content}}([sS]*)$/g;
var result = regexp.exec(layout);

var templateWithLayout = result[1] + element.html() + result[2];
element.html($compile(templateWithLayout)(scope));
});
}
}


});



My problem:



When I'm using scope variables in template (in layout template or inside of layout tag), eg. {{whatever}} it just work initially. If I update the whatever variable, the directive is not updated anymore. The whole link function will just get triggered once.



I think, that AngularJS does not know, that this directive uses scope variables and therefore it will not be updated. But I have no clue how to fix this behavior.


More From » angularjs

 Answers
31

You should create a bound scope variable and watch its changes:



return {
restrict: 'E',
scope: {
name: '='
},
link: function(scope) {
scope.$watch('name', function() {
// all the code here...
});
}
};

[#74193] Monday, November 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;