Angular.js Controllers: Changing a Model Value with a Controller Function

19 February, 2013

This is a post of a series 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 increment a model value by 1.

Solution #

Implement an increment function which changes the scope.

We use the ng-init Directive to call the incrementValue function in the template.

<div ng-controller="MyCtrl">
<p ng-init="incrementValue(5)">{{value}}</p>

The controller defines the default value and the incrementValue function.

function MyCtrl($scope) {
$scope.value = 1;

$scope.incrementValue = function(value) {
$scope.value += 1;

Discussion #

The ng-init directive is executed on page load and calls the function defined in MyCtrl.

You can find the complete example on Github.