Thiatt
Thiatt

Reputation: 574

scope variable undefined in directive link function

I have a directive which has this piece of code:

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

For some reason, the first time I navigate to the view that contains this directive everything works fine, but from the second time onwards I always get a Cannot call method 'forEach' of undefined error. I read through some similar questions on SO which mentioned interpolated attributes not being instantly available on the link function, so they reccomended the use of $observe. I even added a console.log(scope) and the modules property shows up on the object. Any idea of what might be causing this?

Upvotes: 2

Views: 2809

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

It should be rather $scope.$watch rather that attrs.$observe as $observe required @ in isolated scope of directive & on html it would be modules="{{module}}", For big object DOM will get messed up so I'd prefer you to use $watch which make sense

Code

scope.$watch("modules", function(newVal) {
    if(newVal){
        scope.modules.forEach(function(module) {
            module.open = false;
        });
    }
});

Upvotes: 1

Related Questions