【发布时间】: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);
}
}
});
谢谢。 戈尔比。
【问题讨论】:
-
当你使用带 ^ 符号的 require 时,你不是说 taskBar 指令必须是 extWindow 的父级吗?我已经做了很多这样的指令,没有问题。不过,您需要嵌入父指令才能使其正常工作。
标签: angularjs scope require directive