doranT doranT - 3 months ago 14
AngularJS Question

What's an elegant way of accessing parent controller's member from child controller?

I am using controllerAs syntax in my application, I want to access parent controller's function from child controller, I know this is achievable by injecting $scope, however considering Angular has tried so hard to get rid of the $scope from code, I'd like to know if there is a more elegant way of doing this without injecting $scope?

Here's an example of HTML:

<div ng-controller="AppCtrl as app">
<div ng-controller="ChildCtrl as child">
</div>
</div>


And corresponding controllers:

angular.module('test').controller('AppCtrl', function () {
var vm = this;
vm.log = function() {
console.log("Output");
}
}

angular.module('test').controller('ChildCtrl', function () {
var vm = this;
// Here I want to access parent's log() function
}


I know I can inject $scope and then access the log function by
$scope.app.log()
, but is there a bettter way to access log without injecting the
$scope?

Answer

One option would be to use Angular 1.5 components.

Here is example of Intercomponent Communication.

And Components docs.

It would look something like this in child component:

.component('childComponent', {
  require: {
    parentCtrl: '^ parentCtrl'
  }
  controller: function() {
    this. parentCtrl.anyMethod(); //here we are accessing parent's controller properties
  }

  ...

});