angularjs – 什么是“require”的指令定义对象采取?

前端之家收集整理的这篇文章主要介绍了angularjs – 什么是“require”的指令定义对象采取?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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为例。

  1. angular.module('ui.bootstrap.tabs',[])
  2. .controller('TabsController',['$scope','$element',function($scope,$element) {
  3. ... // omitted for simplicity
  4. }])
  5. .directive('tabs',function() {
  6. return {
  7. restrict: 'EA',transclude: true,scope: {},controller: 'TabsController',templateUrl: 'template/tabs/tabs.html',replace: true
  8. };
  9. })
  10. .directive('pane',['$parse',function($parse) {
  11. return {
  12. require: '^tabs',restrict: 'EA',scope:{
  13. heading:'@'
  14. },link: function(scope,element,attrs,tabsCtrl) {
  15. ... // omitted for simplicity
  16. },templateUrl: 'template/tabs/pane.html',replace: true
  17. };
  18. }]);

pane指令需要:’^ tabs’,其中tabs是其父元素上的指令的名称,而附加到该指令的控制器的名称是TabsController。从我自己的解释上面的定义,它应该已经要求:’^ TabsController’不需要:’^ tabs’,这显然是错误。请告诉我在我的理解中我错过了什么。

文档的这个特定主题确实令人困惑,但是奇怪的是,它似乎是所有有意义的。

理解这个定义背后的逻辑的关键是理解“指令控制器”指的是指令的控制器实例,而不是控制器工厂。

在tabs选项卡示例之后,当创建tabs元素时,还会创建一个新的TabsController实例并附加到该特定元素数据,如:

  1. tabElement.data('$tabsController',tabsControllerInstance)

窗口元素上的require:’^ tabs’基本上是对父标签元素上使用的特定控制器实例(tabsControllerInstance)的请求。

猜你在找的Angularjs相关文章