HTML5 Zone is brought to you in partnership with:

I am a Software developer working on Microsoft technologies and Web technologies. Very passionate about exploring and sharing my learnings Ravi is a DZone MVB and is not an employee of DZone and has posted 25 posts at DZone. You can read more from them at their website. View Full User Profile

“Controller as” Syntax in Angular JS 1.2

  • submit to reddit

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(){"Ravi";
<div ng-app ng-controller="HomeCtrl as vm">
 <input type="text" ng-model="" />

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 Ravi Kiran, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)