相关疑难解决方法(0)

如何通过递归要求访问父指令的控制器?

我试图以递归方式到达父"box"指令的控制器:

<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>
Run Code Online (Sandbox Code Playgroud)

我希望控制器变量undefined在链接函数中,但我得到实际box指令的控制器.

所以我的问题是......在这种情况下如何访问PARENT控制器:

<box>
    <box></box>
</box>
Run Code Online (Sandbox Code Playgroud)

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

angularjs angularjs-directive angularjs-controller

20
推荐指数
2
解决办法
2万
查看次数

Angularjs:将所需的指令控制器注入控制器而不是链接功能

角度正常的用例

如果您有父指令和子指令,则在父指令的控制器中创建方法,并在子指令中需要父控制器.Angular会将父控制器传递给子指令链接函数.

我的用例

我有一个用例,其中child指令是另一个指令的父指令.我在指令中间的指令上面有指令.中间指令是底部最后一个指令所必需的.

在一个简单的世界中,我可以为中间指令创建一个链接方法和一个控制器.link方法使用顶层控制器处理所有内容,中间控制器传递给bottom指令.

在我的情况下,中间指令的控制器中的方法必须调用父级中的方法,所以我需要中间控制器中的顶级控制器而不是中间指令的链接功能!

问题

如何将所需的控制器注入控制器而不是链接功能

angular.module('app').directive('top', function () {
    return {
        $scope: true,
        templateUrl: "top.html",
        controller: function() {
            this.topMethod = function() {
                // do something on top
            }
        }
    }
});

angular.module('app').directive('middle', function () {
    return {
        $scope: true,
        templateUrl: "middle.html",
        require: "^top",
        controller: function($scope, $attrs, topController) {
            this.middleMethod = function() {
                // do something in the middle

                // call something in top controller, this is the part that makes everything so complicated
                topController.topMethod();
            }
        }
    } …
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-directive

15
推荐指数
3
解决办法
2万
查看次数