Anh Trinh JavaScript Developer

One directive, multiple controllers & controllerAs

You can pass multiple controller in to the require property while declaring a directive

app.directive('myDirective', function () {
  return{
    restrict: "A",
    require:['^parentDirective', '^ngModel'],
    link: function ($scope, $element, $attrs, controllersArr) {

      // parentDirective controller
      controllersArr[0].someMethodCall();

      // ngModel controller
      controllersArr[1].$setViewValue();
    }
  }
});

Want to use controllerAs syntax for your child directive, but still want to access parent directive’s controller?

app.directive('myDirective', function () {
  return{
    restrict: "A",
    require:['^parentDirective', 'myDirective'],
    controller: 'myDirectiveController',
    controllerAs: 'childVm',
    link: function ($scope, $element, $attrs, ctrls) {
		var parentCtrl = ctrls[0];

        var childVm = ctrls[1];

        // and do stuffs
    }
  }
});