2

Is it possible to have a parent directive and a child directive, both with their own controller?

Something like:

.controller('ParentController', function () {
    var self = this;

    self.action = function () {
        console.log('parent action');
    }
})

.controller('TestSomethingController', function () {
    var self = this;

    self.something = function () {
        console.log('something');
    }
})

.directive('parent', function () {
    return {
        restrict: 'A',
        controller: 'ParentController',
        link: function (scope, element, attrs, controller) {
            controller.action();
        }
    }
})

.directive('test', function () {
    return {
        restrict: 'A',
        require: 'parent',
        controller: 'TestSomethingController',
        link: function (scope, element, attrs, controller) {
            controller.something();
        }
    };
});

I tried to do this one codepen like this:

http://codepen.io/r3plica/pen/bdygeP?editors=101

If I remove the require, it obviously works, but I would like to keep the require. Does anyone know if that is possible?

1 Answer 1

2

You can require multiple directives. Have it require itself as well as parent. With this syntax, the last parameter of link will be an array of the controllers of the given directives.

.directive('test', function () {
    return {
        restrict: 'A',
        require: ['parent', 'test'],
        controller: 'TestSomethingController',
        link: function (scope, element, attrs, controllers) {
            controllers[0].action();    // parent
            controllers[1].something(); // self
        }
    };
});

Here is a forked, working version of your CodePen.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.