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

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

问题描述

我创建了一个指令,将 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天全站免登陆