Accessing the scope inside the $timeout in angularjs

时间:2017-11-13 06:12:16

标签: angularjs

I have a directive in AngularJS, with $timeout in link function.

.directive('setValueInColorSelectionBlock', function($timeout) {
    return {
        restrict:'A',
        scope:{
            setValueInColorSelectionBlock:"=setValueInColorSelectionBlock"
        },
        link:function(scope, element, attrs) {
           //able to access the scope
             $timeout(function() {
               //not able to access the scope 
            });
        }
    };
});

My html :

<div class="container-fluid" set-value-in-color-selection-block="$tbCtrl.containers">

this in $time out access the window object. I am not able to access scope inside the $timeout.

How do we access the scope?

2 个答案:

答案 0 :(得分:0)

According to the current scope configuration of your directive, you are telling angular to bind your scope to a variable in the parent scope. The name of the variable is set to be decided by the value of the element attribute setValueInColorSelectionBlock.

And your scope will have a single property - that is setValueInColorSelectionBlock.

Make sure all the variable and attribute requirements to satisfy these conditions are met.

If everything is set, the scope is available inside the timeout function through link functions scope argument.

link:function(scope, element, attrs) {

             $timeout(function() {
               console.log(scope);
            });

        }

Edit

When the scope is referenced inside the timeout function, a closure is created. This closure makes sure that the local variables are still accessible even after the caller function is left.

Now, based on the comment, your problem seems to be that, even though the scope object is ensured by the closure, the properties of it may be deleted by the time the timeout function is executed.

You can probably take the copy of the scope object and save it to the local function scope for later access.

link:function(scope, element, attrs) {

             var savedScope = angular.copy(scope);

             $timeout(function() {
               console.log(savedScope);
            });

        }

答案 1 :(得分:0)

类似于 @Charlie H 关闭的答案。您可以尝试此操作,将$timeout包含带参数的函数和用户参数放入$timeout函数。

function(eleScope){ // wrapper function with eleScope as parameter
           $timeout(function() {
               console.log(eleScope); // access eleScope paramter
        })(scope); // pass scope to closure function
    }
}