1

I'm following an exercise in a book, so I don't know if I'm doing any mistake. I have two controllers both with a function with same name:

app.controller('externalController', ['$scope', function(scope){
  scope.aFunction(){
  //Some code...
  };
}]);

app.controller('innerController', ['$scope', function(s){
  s.aFunction(){
  //Some code...
  };
}]);

In the book, the function of the external controller is calles in this way:

<div ng-controller="externalController as Ext">
  <div ng-controller="innerController">
    <button ng-click="Ext.aFunction()>Button</button>
  </div>
</div>

this doesn't work for me, can anyone tell me if I'm doing any mistake or if there's something wrong in the code? Thanks a lot. mauro

Mauro Ghiglia
  • 305
  • 1
  • 11

1 Answers1

0

Basically your are using controller as syntax, and you bounded aFunction inside controller $scope rather you should be bound it to controller this.

When using controllerAs syntax controller variables and method should bounded to this(context) and when you use controller as the controller context(this) exposed on HTML via its alias

app.controller('externalController', [function() {
  var Ext = this;
  Ext.aFunction = function() {
    alert('Function Called');
    //Some code...
  };
}]);

app.controller('innerController', [function() {
  var inner = this;
  inner.aFunction = function() {
    //Some code...
  };
}]);

Working Plunker

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299