Angular.js Controllers - Assigning a Default Value to a Model

Published 15 Feb 2013

This is the first of a series of posts about Angular.js, the Superheroic Javascript MVW Framework. It is extracted from my ebook Recipes with Angular.js. If you like this post please support me and buy it!

Problem

You want to assign a default value to the scope in the controllers context.

Solution

Use the ng-controller directive in your template:

<div ng-controller="MyCtrl">
  <p>{{value}}</p>
</div>

And define the scope variable in your controller function:

var MyCtrl = function($scope) {
  $scope.value = "some value";
};

Discussion

Depending on where you use the ng-controller directive, you define its assigned scope. The scope is hierachical and follows the DOM nodes hierarchy. In our example the value expression is correctly evaluated to some value, since value is set in the MyCtrl controller.

Note, that this would not work if the value expression is moved outside the controllers scope:

<p>{{value}}</p>

<div ng-controller="MyCtrl">
</div>

In this case {{value}} will simply be not rendered at all.

You can find the complete example on Github.