Over a million developers have joined DZone.
Platinum Partner

“Controller as” Syntax in Angular JS 1.2

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

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!

The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Rabi (ravi) Kiran , DZone MVB .

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}