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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With