AngularJS simple controller tutorial to increment a value

Angularjs basic controller example to initialize a number in view, and then increment it on button click. We’ll use controller, template and ng-click directive. The final outcome will look like the following screenshot.

angular-controller-increment-number

<div ng-app="myApp" ng-controller='MyCtrl'>
  <p>val={{val}}</p>
  <button ng-click="inc();">click to increment</button>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
var module = angular.module('myApp', []);
module.controller('MyCtrl', function($scope) {
  $scope.val = 1;
  $scope.inc = function() {
    $scope.val += 1;
  };
});
</script>
refresh

Few points to note

  1. When controller is created, the val is initialized to 1 using $scope.val = 1;.
  2. ng-click can take any javascript code. We could have also just used ng-click="val+=1;" also.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments