3

I'm new to AngularJS. I would like to know what the difference is between the following two code snippets:

I. Code that defines a controller using this:

var app = angular.module('greeting', []);
app.controller('HelloCtrl', function() {
  this.name = 'Hello World';
});

II. Code that defines a controller using $scope:

var app = angular.module('greeting', []);
app.controller('HelloCtrl', function($scope) {
  $scope.name = 'Hello World';
});

Thanks.

John Sonderson
  • 3,238
  • 6
  • 31
  • 45

2 Answers2

1

'this' is referring to the instance of your HelloCtrl... $scope is an entirely different object that's already got state and is managed through angular

beauXjames
  • 8,222
  • 3
  • 49
  • 66
1

The two implementations are used differently in the view. The this syntax is used together with the controller as syntax, which essentially makes your controller your view model.

controller as example

In Controller

this.text = "Controller as example"

In View

<div ng-controller="myCtrl as controllerViewModel">
    {{controllerViewModel.text}}
</div>

Scope equivalent

In Controller

$scope.text = "Scope example";

In View

<div ng-controller="myCtrl">{{text}}</div>

Here are some usefull links regarding the subject

https://docs.angularjs.org/api/ng/directive/ngController

http://toddmotto.com/digging-into-angulars-controller-as-syntax/

https://thinkster.io/egghead/experimental-controller-as-syntax/

Stefan Bergh
  • 106
  • 3