简体   繁体   中英

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 .

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.

hello
undefined
Contacts init

What should I do if I want to be able to access the test2 variable?

You will need to use the require property inside your directive. This will make the scope of the defined controllers available inside the link function as 4th argument. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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