2

I'm pretty new to Angular, so forgive me for the remedial question. I've searched SO briefly for an answer, but can't seem to find one directly related.

In most examples, I've seen $scope passed around to controllers, but there are some where they use this on the controller function object itself to store model state. Is there any benefit to using one over the other?

These two seem to behave the same way, but I'm curious if there's benefit to one of these over the other.

var myApp = angular.app('MyApp', []);
myApp.controller('PersonController', function() {
  this.name = 'Bob';

  this.setName = function(name) {
    this.name = name;
  };
});

myApp.controller('PersonController1', ['$scope', function($scope) {
  $scope.name = 'Bob';

  $scope.setName = function(name) {
    $scope.name = name;
  };
});

The biggest difference seems to be in using them on the view - $scope properties are accessed using simply the name, whereas when the controller uses itself to store state, it has to be accessed using dot-notation.

<div ng-controller="PersonController as pc">
  {{pc.name}}
</div>

<div ng-controller="PersonController1 as pc">
  {{name}}
</div>

Is the difference simply a matter of taste? Or are there additional things going on that will later bite me if I choose one method over the other?

Colselaw
  • 1,069
  • 9
  • 21

0 Answers0