我有兩個angularjs指令(extWindow和taskBar),並且想要將taskBar的控制器注入extWindow以訪問它的作用域。因爲它們不共享我使用的相同範圍AngularJS - 無法在另一個指令中訪問指令控制器
require : '^$directive'
語法包含它。 這樣做,我可以擺脫'指令'extWindow'所需的錯誤「控制器'taskBar',找不到'!但TaskBarCtrl在extWindow指令的鏈接(..)方法中仍未定義。
任何建議如何解決它?
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);
}
}
});
謝謝。 golbie。
當您使用的^符號需要,是不是有效說taskBar指令必須是extWindow的父級?我已經提出了很多像這樣的指令,沒有任何問題。你需要透過父指令來使它工作。 – natwallbank 2014-10-28 23:25:02