【问题标题】:accessing rootScope in directive在指令中访问 rootScope
【发布时间】:2016-03-23 03:34:53
【问题描述】:

我已经尝试了一百万种方法来从这个基于 elasticui 的指令中访问 rootScope 变量,但运气为零。这是指令,记住 $rootScope 确实被传递到它的父控制器中。

var elasticui;
(function (elasticui) {
var directives;
(function (directives, rootScope) {
    var IndexDirective = (function () {
        function IndexDirective() {
            var directive = {};
            directive.restrict = 'EAC';
            directive.controller = elasticui.controllers.IndexController;
            directive.link = function (scope, element, attrs, indexCtrl, rootScope) {
            console.log("Updated Index: " + $rootScope.esIndex);
            indexCtrl.indexVM.index = scope.$eval(attrs.euiIndex);
            };
            return directive;
        }
        return IndexDirective;
    })();
    directives.IndexDirective = IndexDirective;
    directives.directives.directive('euiIndex', IndexDirective);
})(directives = elasticui.directives || (elasticui.directives = {}));
})(elasticui || (elasticui = {}));

在其他地方,我将 $rootScope.esIndex 设置为我想指向的索引,但我得到“$rootScope is not defined”。我尝试将指令的范围属性设置为 false,尝试在 $rootScope.esIndex 上设置一个观察者作为链接函数返回值的一部分,但无论我做什么,我似乎都无法弄清楚。

我认为对我来说问题的一部分是,从指令的角度来看,这个结构有点神秘,对于一个新的有角的人来说是消化的。这是一组更大的指令定义中的一个块,所以我很难掌握。

有什么想法可以在这里轻松获取 $rootScope 吗?

提前感谢 TON!

【问题讨论】:

  • 您绝对应该在这里提供更多代码,但我会说乍一看您将rootScope 传递给函数,而不是$rootScope。这可能是问题的一部分。

标签: javascript angularjs elasticui


【解决方案1】:

查看更多代码会有所帮助。特别是当你说“$rootScope 确实被通过了”时。但是,由于信息有限,您为什么不尝试更改此行:

(directives = elasticui.directives || (elasticui.directives = {}));

类似

(directives = elasticui.directives || (elasticui.directives = {}, rootScope));

乍一看,您的自执行函数似乎没有被传递它期望的 rootScope 参数。祝你好运!

编辑:也

console.log("Updated Index: " + $rootScope.esIndex);

应该没有美元符号。

编辑:评论有更多信息!

【讨论】:

  • 这是对以下代码的修改,请参见第 179 行 github.com/YousefED/ElasticUI/blob/master/dist/elasticui.js 我试图以类似的方式结束: indexCtrl.indexVM.index = $rootScope.esIndex;如果我在页面的控制器中注销 $rootScope.esIndex ,我会得到正确的值,并且似乎 rootScope 确实被传递到上面的父控制器中,但是我似乎无法从指令本身中访问它。在我的版本中,我杀死了观察者只是为了简化它,但是是的,上面的页面是我正在使用的。
  • 您需要像他们在第 294 行所做的那样声明一个注入的 $rootScope 服务,然后它可以作为参数传递给您的函数,如第 276 行所示。所以您将拥有 IndexDirective.$inject = ['$rootScope'];然后 function IndexDirective($rootScope).... 也将 rootScope 从你不需要的链接函数的参数中取出。
  • 附言。 “vanilla”Angular 不是这样的,我对 elasticui 不熟悉,但我同意它的语法有点神秘。
猜你喜欢
  • 2016-05-30
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多