The Controller we have made can be instantiated and used using controller as
Syntax. That's because we have put variable directly on the controller class and not on the $scope
.
Using controller as someName
is to seperate the controller from $scope
itself.So, there is no need of injecting $scope as the dependency in the controller.
Traditional way :
// we are using $scope object.
app.controller('MyCtrl', function ($scope) {
$scope.name = 'John';
});
<div ng-controller="MyCtrl">
{{name}}
</div>
Now, with controller as
Syntax :
// we are using the "this" Object instead of "$scope"
app.controller('MyCtrl', function() {
this.name = 'John';
});
<div ng-controller="MyCtrl as info">
{{info.name}}
</div>
If you instantiate a "class" in JavaScript, you might do this :
var jsClass = function () {
this.name = 'John';
}
var jsObj = new jsClass();
So, now we can use jsObj
instance to access any method or property of jsClass
.
In angular, we do same type of thing.we use controller as syntax for instantiation.