我正在尝试递归地访问父“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>
最佳答案
自 Angular 1.3 起,您可以使用两个重音符号 ^^
来“仅”在父元素中搜索指令。
(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/