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.
<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>
Few points to note
-
When controller is created, the val is initialized to 1 using
$scope.val = 1;
. -
ng-click can take any javascript code. We could have also just used
ng-click="val+=1;"
also.