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

标签 angularjs angularjs-directive angularjs-controller

我正在尝试递归地访问父“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/

相关文章:

javascript - 带有 ng-repeat 的空表行,AngularJS

javascript - 如何通过 Angular 将鼠标悬停在另一个元素上时添加和删除一个元素的类?

javascript - 指令没有正确获取属性

javascript - 使用 ng-messages 对生成的字段进行表单验证

javascript - 有没有办法让子 Controller 从其父 Controller 继承服务 "like"实例?

由于 $compile,Javascript(Angular)嵌套指令加载两次

javascript - 使用来自后端的 Regexp 进行 Angular 电子邮件验证

javascript - Angular 指令不工作 Chrome 打包应用程序

AngularJS:为什么不在 Controller 中编写逻辑?

angularjs - Angular-ui 引导模式,无需创建新 Controller