Reputation: 446
In recent 1.2.x angular versions (maybe also older) controllers can be initialized using expression as
<div ng-controller="demoController as vm"></div>
The documentation explains this as:
The controller instance can be published into a scope property by specifying as propertyName.
http://code.angularjs.org/1.2.4/docs/api/ng.directive:ngController
In which scenarios does this help?
Upvotes: 1
Views: 273
Reputation: 28130
The controller is instantiated with new
, so it's a prototypical object. Meaning it can have prototype methods. However the methods are called from the view as unbound methods with "this" set to the scope. This largely defeats the purpose of it being a prototypical object, since "this" inside the methods can't reach the object instance.
There's actually been some back and forth on this... Angular pre-1.0 used "this" as the controller instance, I forget exactly how that worked, maybe the controller instance and scope were one and the same. With Angular 1.2+ it's a bit of a return to that style, to treat the controller functions more as constructors than as merely collections of functions.
In this new 1.2 style, you only ever add one thing to the scope (the controller instance) and reference all the data off of that. This has the benefit of working with controllers that are in a "class like" constructor form with prototype methods, and conveniently defeats the common gotcha of writing to an ng-model that's in a scope more inner than your realized. The workaround for that is including a dot somewhere in your lvalue expression.
Upvotes: 1
Reputation: 18523
Using the controller as syntax has a few advantages:
If you're using a language like typescript
or coffeescript
then you can easily use a class for your controller:
//TypeScript example
class MyCtrl {
name: string = "";
constructor(private $log) {
$log.info("Initializing MyCtrl");
}
doSomething() {
this.name = "foo"
}
}
sample view
<div ng-controller="MyCtrl as ctrl">
<span ng-click="ctrl.doSomething()">{{ctrl.name}}</span>
</div>
And even if your not using coffeescript
or typescript
you can do the same thing with prototypes....it just looks a bit uglier.
If you have multiple controllers in a view then using the "controller as" syntax will ensure that you don't have any naming conflicts
For beginners to angular using $scope can be confusing
Upvotes: 0