范围变量在指令链接函数中未定义

时间:2015-07-21 11:42:53

标签: javascript angularjs angularjs-directive ionic-framework ionic

我有一个包含这段代码的指令:

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属性显示在对象上。知道可能导致这种情况的原因吗?

1 个答案:

答案 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;
        });
    }
});