Recently, I created a small directive that wraps its contents with another template file. The objective is to transform the code like this:
<layout name="Default">My cool content</layout>
into this output:
<div class="layoutDefault">My cool content</div>
This transformation happens because the layout "Default" contains the following code:
<div class="layoutDefault">{{content}}</div>
Here's the code snippet 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 = /^([\s\S]*?){{content}}([\s\S]*)$/g;
var result = regexp.exec(layout);
var templateWithLayout = result[1] + element.html() + result[2];
element.html($compile(templateWithLayout)(scope));
});
}
}
});
However, I encountered an issue:
Whenever I use scope variables in the templates (inside the layout template or within the layout tag), such as {{whatever}}
, it only works initially. Subsequent updates to the variable whatever
do not trigger any changes in the directive. It seems like the entire link function is executed only once.
I suspect that AngularJS fails to recognize the usage of scope variables in this directive, causing the lack of updates. Unfortunately, I am unsure how to resolve this behavior.