0

I'm building an Angular controller using controller as syntax:

<body ng-controller="ctrl as myCtrl">
  <p>accessed via scope resolution: {{ foo }} </p>
  <p>accessed via controller resolution: {{ myCtrl.foo }}</p>
</body>

In the controller I have this:

myApp.controller('ctrl', function($scope) {
  this.foo = 'Controller\'s foo';
  $scope.foo = '$scope\'s foo';
});

The code above works and prints bot controller's foo and $scope's foo.

  • Why?
  • Is this just a case of "unspecified behavior"?
  • Is there ever a time when you would want to use both in the real world?
Rick
  • 8,366
  • 8
  • 47
  • 76
  • 1
    From the documentation: The controller instance can be published into a scope property by specifying ng-controller="as propertyName". So propertyName.foo is referring to $scope.foo – geckob Jan 26 '16 at 01:30
  • Additionally, there are times when you'll want to inject $scope if you have event listeners (`$scope.$on()`) or need to explicitly watch (`$scope.$watch()`) a variable or function return value, even when using 'controller as' syntax. I found [this article very helpful](https://toddmotto.com/digging-into-angulars-controller-as-syntax/) in explaining why. – Bennett Adams Jan 26 '16 at 02:17
  • Please refer below link, in-detail explanation http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers – Manas Jan 31 '16 at 08:33

1 Answers1

1

Very good in details explanation at

http://codetunnel.io/angularjs-controller-as-or-scope/

Hope this helps !

Manas
  • 26
  • 3