require – Require another controller be passed into current directive
linking function. The require takes a name of the directive controller
to pass in. If no such controller can be found an error is raised. The name can be prefixed with:
- ? – Don’t raise an error. This makes the require dependency optional.
- ^ – Look for the controller on parent elements as well.
以上是官方文档的定义。这里的歧义是什么是“指令控制器”。
以tabs directive from the angularjs-ui bootstrap project为例。
angular.module('ui.bootstrap.tabs',[])
.controller('TabsController',['$scope','$element',function($scope,$element) {
... // omitted for simplicity
}])
.directive('tabs',function() {
return {
restrict: 'EA',transclude: true,scope: {},controller: 'TabsController',templateUrl: 'template/tabs/tabs.html',replace: true
};
})
.directive('pane',['$parse',function($parse) {
return {
require: '^tabs',restrict: 'EA',scope:{
heading:'@'
},link: function(scope,element,attrs,tabsCtrl) {
... // omitted for simplicity
},templateUrl: 'template/tabs/pane.html',replace: true
};
}]);
pane指令需要:’^ tabs’,其中tabs是其父元素上的指令的名称,而附加到该指令的控制器的名称是TabsController。从我自己的解释上面的定义,它应该已经要求:’^ TabsController’不需要:’^ tabs’,这显然是错误。请告诉我在我的理解中我错过了什么。
文档的这个特定主题确实令人困惑,但是奇怪的是,它似乎是所有有意义的。
理解这个定义背后的逻辑的关键是理解“指令控制器”指的是指令的控制器实例,而不是控制器工厂。
在tabs选项卡示例之后,当创建tabs元素时,还会创建一个新的TabsController实例并附加到该特定元素数据,如:
tabElement.data('$tabsController',tabsControllerInstance)
窗口元素上的require:’^ tabs’基本上是对父标签元素上使用的特定控制器实例(tabsControllerInstance)的请求。