简体   繁体   English

在Angular指令中访问父控制器

[英]Accessing parent controller in an Angular directive

I have directive that dynamically sets the header bar content for a given application state. 我有指令,可以动态设置给定应用程序状态的标题栏内容。

I would like to be able to access the functions and variables in the Controller of the current view, but I am only ever able to access my RootCtrl . 我希望能够访问当前视图的Controller中的函数和变量,但是我只能访问RootCtrl

The directive looks like this. 该指令如下所示。

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);
    }
}

And the controllers. 和控制器。

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

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

And when I navigate to the contacts state, the output looks like this. 当我导航到contacts状态时,输出如下所示。

hello
undefined
Contacts init

What should I do if I want to be able to access the test2 variable? 如果我想能够访问test2变量,该怎么办?

You will need to use the require property inside your directive. 您将需要在指令中使用require属性。 This will make the scope of the defined controllers available inside the link function as 4th argument. 这将使链接函数内定义的控制器的范围可作为第4个参数使用。 You can access the scopes as an array inside the link function then. 然后,您可以在链接函数内以数组形式访问范围。

Your code may look like: 您的代码可能如下所示:

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);
    }
}

See the Angular documentation for Directives for some more examples (under the title Creating Directives that Communicate ) and the explanation of the ^controller syntax. 有关更多示例,请参见Angular文档中的指令 (标题为创建可通信的指令下)和^controller语法的说明。

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

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