gpt4 book ai didi

angularjs - 如何通过递归请求来访问父指令的 Controller ?

转载 作者:行者123 更新时间:2023-12-03 06:27:16 25 4
gpt4 key购买 nike

我正在尝试递归地访问父“box”指令的 Controller :

<body ng-app="main">

<!-- no nesting: parent is the just body -->
<box></box>

<script type="text/javascript">
angular.module('main', [])
.directive('box', function() {
return {
restrict: 'E',
controller: function() { },
require: '?^box', // find optional PARENT "box" directive
link: function(scope, iElement, iAttrs, controller) {
// controller should be undefined, as there is no parent box
alert('Controller found: ' + (controller !== undefined));
}
};
});
</script>
</body>

我希望 Controller 变量在链接函数中未定义,但我得到了实际框指令的 Controller 。

所以我的问题是......在这种情况下如何访问父 Controller :

<box>
<box></box>
</box>

http://jsfiddle.net/gjv9g/1/

最佳答案

自 Angular 1.3 起,您可以使用两个重音符号 ^^ 来“仅”在父元素中搜索指令。

引自 Angular Docs on require :

  • (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  • ? - Attempt to locate the required controller or pass null to the link fn if not found.
  • ^ - Locate the required controller by searching the element and its parents. Throw an error if not found.
  • ^^ - Locate the required controller by searching the element's parents. Throw an error if not found.
  • ?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.
  • ?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.

根据您的情况,请将 require: '?^box', 替换为 require: '?^^box',

关于angularjs - 如何通过递归请求来访问父指令的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19340495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com