从另一个指令访问指令的范围变量 [英] Accessing a directive's scope variable from another directive

查看:96
本文介绍了从另一个指令访问指令的范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一条指令,将pageYOffset绑定到窗口滚动时的作用域变量,如下所示:

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

我正在尝试从另一个指令访问watchScroll变量,如下所示:

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?

我有一个单独的scrollDirective的原因是,我将在整个应用程序中使用pageYOffset,并且我希望它是一个全局变量,这样我就不必在需要的每个指令中都创建该函数.将来.

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.

推荐答案

在scope.watchScroll = pageYOffset之后添加了scope.$ apply();一切都很好.

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

这篇关于从另一个指令访问指令的范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆