Tuesday 19 November 2013

“Controller as” Syntax in Angular JS 1.2

Angular JS 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 Angular JS 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(){
    this.name="Ravi";
}

<div ng-app ng-controller="HomeCtrl as vm">
 <input type="text" ng-model="vm.name" />
 <br  />
 <span>{{vm.name}}</span>
</div>


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. Following snippet shows the syntax:

app.config(function($routeProvider){
    $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 own 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 template of the directive. It is shown below:
app.directive("helloDir", function(){
    return{
        restrict:'A',
        template:"<span>{{dir.message}}</span>",
        controller:function(){
            this.message="Good Morning!";
        },
        controllerAs:"dir"
    }
});
This directive would render the message "Good Morning" when used in a view.
Happy coding!

4 comments:

Note: only a member of this blog may post a comment.