Accessing a directive's scope variable from another directive

青春壹個敷衍的年華 提交于 2019-12-12 03:23:21

问题


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..).



来源:https://stackoverflow.com/questions/28140817/accessing-a-directives-scope-variable-from-another-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!