AngularJS 指令不会在范围变量更改时更新 [英] AngularJS directive does not update on scope variable changes
问题描述
我尝试编写一个小指令,用另一个模板文件包装它的内容.
此代码:
我很酷的内容
应该有这个输出:
我很酷的内容
因为布局默认"有这个代码:
{{content}}
这里是指令的代码:
app.directive('layout', function($http, $compile){返回 {限制:'E',链接:功能(范围,元素,属性){var layoutName = (angular.isDefined(attributes.name)) ?属性名称:'默认';$http.get(scope.constants.pathLayouts + layoutName + '.html').成功(功能(布局){var regexp =/^([\s\S]*?){{content}}([\s\S]*)$/g;var 结果 = regexp.exec(layout);var templateWithLayout = result[1] + element.html() + result[2];element.html($compile(templateWithLayout)(scope));});}}
});
我的问题:
当我在模板中(在布局模板中或在布局标签内部)使用范围变量时,例如.{{whatever}}
它只是最初工作.如果我更新 whatever
变量,则指令不再更新.整个链接功能只会被触发一次.
我认为,AngularJS 不知道该指令使用范围变量,因此不会更新.但我不知道如何解决这种行为.
你应该创建一个绑定作用域变量并观察它的变化:
return {限制:'E',范围: {名称:'='},链接:功能(范围){scope.$watch('name', function() {//这里的所有代码...});}};
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 = /^([\s\S]*?){{content}}([\s\S]*)$/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.
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...
});
}
};
这篇关于AngularJS 指令不会在范围变量更改时更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!