【发布时间】:2015-05-12 07:52:40
【问题描述】:
我正在使用 ng-repeat,我需要将范围变量传递给指令的编译函数。我知道如何使用链接功能,但不知道如何使用编译功能。
我的 html 看起来像:
<div ng-repeat="item in chapter.main">
<block type="item.type"></block>
</div>
不管项目是什么,我们都说 item.type="blah"。 那么这个链接功能就可以正常工作了
app.directive('block', function() {
return {
restrict: 'E',
link: function(scope, element, attributes){
scope.$watch(attributes.type, function(value){
console.log(value); //will output "blah" which is correct
});
}
}
});
但是我不能对编译做同样的事情?
app.directive('block', function() {
return {
restrict: 'E',
compile: function(element, attrs, scope) {
scope.$watch(attrs.type, function(value){
console.log(value);
});
}
}
});
我得到的错误是“无法读取未定义的属性 $watch”..
这就是我希望我的指令的样子:
app.directive('block', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
element.append('<div ng-include="\'{{type}}-template.html\'"></div>');
//or element.append('<div ng-include="\'{' + attrs.type + '}-template.html\'"></div>');
//except the above won't interpret attr.type as a variable, just as the literal string 'item.type'
}
}
});
【问题讨论】:
-
这里有一个有趣的article
compile以及它在Angularjs中的工作原理。
标签: angularjs angularjs-directive angularjs-scope