user3783608
user3783608

Reputation: 867

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?

Upvotes: 1

Views: 77

Answers (1)

ConcurrentHashMap
ConcurrentHashMap

Reputation: 5084

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.

Upvotes: 1

Related Questions