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.

0

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.