Accessing a directive's scope variable from an

2019-09-17 06:37发布

问题:

I've created a directive that binds the pageYOffset to a scope variable on window scroll like this:

app.directive('scrollDirective',function(){
    return {
        restrict: 'E',
        link: function(scope,elem,attrs){
            angular.element(window).bind('scroll',function(){
                scope.watchScroll = pageYOffset;
            })
        }
    }
})

And I am trying to access watchScroll variable from another directive like this:

app.directive('anotherDirective',function(){
    return {
        restrict: 'A',
        link: function(scope,elem,attrs){
            scope.$watch(function(){return scope.watchScroll;},function(changes){
                console.log(changes);
            });
        }
    }
})

Am I doing something wrong or scope variables cannot be accessible like this from one directive to another?

The reason why I have a separate scrollDirective is that I will be using the pageYOffset throught the app and I wanted it to be a global variable so that I don't have to create that function in every single directive where I need it in future.

回答1:

Added scope.$apply() after scope.watchScroll = pageYOffset; and it all works great.



回答2:

Yes.You must to call $scope.$apply().Apply function is used to update (trigger) the scope inside some action (Jquery plugins,some jQuery function,setTimeout etc..).