我有一个包含这段代码的指令:
return {
restrict: "E",
scope: {
moduleProgress: "=",
modules: "=",
parentScroll: "="
},
templateUrl: 'app/program/module.list.template.html',
link: function(scope,el,attrs,ctrl,tf) {
$templateRequest("app/program/chapter.list.template.html").then(function(template) {
var template = angular.element(template);
var elements = [];
console.log(scope);
attrs.$observe("modules", function(val) {
scope.modules.forEach(function(module) {
module.open = false;
});
});
出于某种原因,我第一次导航到包含此指令的视图时一切正常,但从第二次开始我总是遇到Cannot call method 'forEach' of undefined
错误。我在SO上阅读了一些类似的问题,提到插值属性不能立即在链接函数上使用,因此他们建议使用$observe
。我甚至添加了console.log(scope)
并且modules
属性显示在对象上。知道可能导致这种情况的原因吗?
答案 0 :(得分:1)
它应该是$scope.$watch
而是attrs.$observe
,而$observe
需要@
在指令的孤立范围内&在html上它会是modules="{{module}}"
,对于大对象DOM会搞砸,所以我更希望你使用$watch
这是有意义的
<强>代码强>
scope.$watch("modules", function(newVal) {
if(newVal){
scope.modules.forEach(function(module) {
module.open = false;
});
}
});