【问题标题】:AngularJS - cannot access directive controller in another directiveAngularJS - 无法访问另一个指令中的指令控制器
【发布时间】:2014-10-28 22:37:13
【问题描述】:

我有两个 angularjs 指令(extWindow 和 taskBar)并且想将 taskBar 的控制器注入 extWindow 以访问它的范围。因为它们与我使用的范围不同

require : '^$directive'

包含它的语法。 这样做我可以摆脱指令'extWindow'所需的错误'Controller'taskBar',找不到!但在 extWindow 指令的 link(..) 方法中,TaskBarCtrl 仍未定义。

有什么建议可以解决吗?

var mod = angular.module('ui', [])
.directive('taskBar', function() {

    var link = function(scope, el, attrs) { 
        $(el).css('display', 'block');
        $(scope.titles).each(function(i,t) {
            el.append('<span>' + t + '</span>')
        });
    };

    return {
        scope: {},
        restrict : 'E',
        controller: function($scope, $element, $attrs) {

            $scope.titles = [];

            this.addTitle = function(title) {               
                $scope.titles.push(w);
            };

            this.removeTitle = function(title) {
                $scope.titles = jQuery.grep(function(n,i) {
                    return title != n;
                });
            }
        },
        link: link
    };
}).directive('extWindow', function() {  

    return {
        scope: {},
        require: '^?taskBar',
        restrict: 'E',
        transclude: true,
        template: '<div class="ui-window">\
            <div class="ui-window-header"><span>{{windowTitle}}</span><div class="ui-window-close" ng-click="close()">X</div></div>\
            <div class="ui-window-content" ng-transclude></div>\
            </div>',
        link: function(scope, element, attrs, taskBarCtrl) {
            scope.windowTitle = attrs['windowTitle'];   
            scope.close = function() {
                $(element).css('display', 'none');
            }
            //taskBarCtrl is not recognized!!!
            taskBarCtrl.addTitle(scope.windowTitle);
        }
    }
});

http://jsfiddle.net/wa9fs2nm/

谢谢。 戈尔比。

【问题讨论】:

  • 当你使用带 ^ 符号的 require 时,你不是说 taskBar 指令必须是 extWindow 的父级吗?我已经做了很多这样的指令,没有问题。不过,您需要嵌入父指令才能使其正常工作。

标签: angularjs scope require directive


【解决方案1】:

如果你的父指令有一个控制器并且你需要类似的东西。

this.scope = $scope;
this.attrs = $attrs;

在你的孩子的链接功能中,你需要类似的东西

var Ctrl = ctrl || scope.$parent.tBarCtrl;

这是Plunker

【讨论】:

  • 嗨,dylan,感谢您提供这个美丽而有效的示例,但我认为它需要讨论。让我解释一下我的发现。
  • 我需要的第一件事是在模块中定义一个控制器。这对指令是可见的(至少对于那些在同一范围内定义的指令)并且可以被控制器引用:'ctrl' .现在第二个指令想通过使用 require: '^?directivename' 来使用另一个指令的控制器。引用它还应该使控制器在链接函数中可用。但是控制器在“黄色”指令中不可用。另一方面,“红色”可以访问控制器,但所做的更改并未填充到模板中。Thx.plnkr.co/edit/HOCi2QlFMA0P77w0OPWL
  • 我终于找到了正确的解决方案。错误是第二个指令没有被第一个包裹。如 api 文档中所述,'^?name' 正在寻找父级的指令。由于两个指令都是同级指令,因此找不到指令,因此未定义 taskBarCtrl。指令之间通信的另一种解决方案可能是将控制器的外部函数传递给它们(& 运算符)。请参阅此解决方案plnkr.co/edit/itEhaA5cfRpxylf6TMZ4?p=preview
  • 是的,我想我对我的示例有点忘乎所以并没有意识到,看起来我的示例依赖于 main 作为父级,而不是我想象的任务栏控制器。
猜你喜欢
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多