Friday, July 11, 2014

Angular.js: controller as syntax

Starting from Angular.js 1.2 a new syntax for your controllers was introduced. This syntax resembles more to an MVVM style of development and completely removes the need of the $scope object inside your controllers. Instead you can just add your objects and methods to “this”.

Let’s have a look how to implement this:

  • The ng-controller attribute value in the html is changed to include the "as" keyword:

<div class="row" ng-controller="ProductsController as vm">

  • Now everywhere you use controller properties or methods inside the html you now need to use the "controller as" alias.

<div class="row" ng-controller="ProductsController as vm">
        <div class="col-md-2">{{vm.product.name}}</div>
        <div class="col-md-2">{{vm.product.price}}</div> 
</div>

  • The controller itself changed also and looks like this:

var app = angular.module("northwindApp", []);

var productsController = function () {
this.product= { 
        name: 'Duvel', 
        category: 'Beer', 
        price: ‘4 €’ 
    }
};

app.controller("ProductsController ", productsController);

No need for the $scope object and just plain JavaScript and the this keyword…

I like it!

1 comment:

Anonymous said...

It's not working.