{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner
css,html5,javascript,tips and tricks,angularjs

“Controller as” Syntax in Angular JS 1.2

AngularJS 1.2 was released around 10 days back and 1.2.1 was released last week with a few fixes. The new release includes a number of significant features. One of them is the controller as syntax.

The classic way of creating a controller in AngularJS is by injecting $scope into it. It creates a new scope corresponding to the controller by inheriting from the parent scope. Angular 1.2 makes it possible to create a controller without injecting $scope into it. Objects and functions of the view are added to controller itself and they are referred in the view using an alias. The scope still exists; it is created and maintained behind the scenes for us. So, we still get the two-way data binding on all objects added to the controller.

Following is a simple controller and the page using it:

function HomeCtrl(){
<div ng-app ng-controller="HomeCtrl as vm">
 <input type="text" ng-model="vm.name" />

We don’t see our good friend $scope in the controller, but the controller looks clean and independent now.

Using "controller as" with routing
To use controller as with routing in multiple views, we need to specify a parameter while configuring the route. The following snippet shows the syntax:

    $routeProvider.when('/first', { templateUrl: 'first.html', controller: 'FirstCtrl', controllerAs:'vm' })
        .when('/second', { templateUrl: 'second.html' , controller: 'FirstCtrl', controllerAs:'vm' })
        .otherwise({ redirectTo: '/first' });

The views can use vm.<object-name> in the data binding expressions.

Using "controller as" in directives
A directive can have a controller of its own. To use controller as in directives, we need to specify an additional property just as in case of routing. The alias can be used in data binding expressions in the  template of the directive. It is shown below:

app.directive("helloDir", function(){
            this.message="Good Morning!";

This directive would render the message "Good Morning" when used in a view.
Happy coding!

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks