繁体   English   中英

在Angular指令中访问父控制器

[英]Accessing parent controller in an Angular directive

我有指令,可以动态设置给定应用程序状态的标题栏内容。

我希望能够访问当前视图的Controller中的函数和变量,但是我只能访问RootCtrl

该指令如下所示。

return {
    restrict: 'EA',
    template: "<div ng-include='getState()'></div>",
    transclude: true,
    scope: false,
    controller: ['$scope', '$state', function($scope, $state) {
        //some logic to retrieve and return the correct header template html
    }],
    link: function(scope, element, attrs){
        console.log(scope.test);
        console.log(scope.test2);
    }
}

和控制器。

.controller('RootCtrl', function($scope, $state, $location, $rootScope) {
    $scope.test = 'hello';
    //...
})

.controller('ContactsCtrl', function($scope, $state, CustomerService) {
    console.log('Contacts init');
    $scope.test2 = 'hello 2';
    //...
})

当我导航到contacts状态时,输出如下所示。

hello
undefined
Contacts init

如果我想能够访问test2变量,该怎么办?

您将需要在指令中使用require属性。 这将使链接函数内定义的控制器的范围可作为第4个参数使用。 然后,您可以在链接函数内以数组形式访问范围。

您的代码可能如下所示:

return {
    restrict: 'EA',
    template: "<div ng-include='getState()'></div>",
    transclude: true,
    scope: false,
    require:['^RootCtrl', '^ContactsCtrl'], 
    controller: ['$scope', '$state', function($scope, $state) {
        //some logic to retrieve and return the correct header template html
    }],
    link: function(scope, element, attrs, requiredControllers){
        console.log(requiredControllers[0].test);
        console.log(requiredControllers[1].test2);
    }
}

有关更多示例,请参见Angular文档中的指令 (标题为创建可通信的指令下)和^controller语法的说明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM