Controller with Action

Description

We can add action handler method in controler and call these method from view. The action can be fired by an anchor link or a form button. We just need to call the method on the controller.

Example


<!doctype html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
</head><!-- w ww.j  a va  2s  .c  o m-->
<body>
  <div ng-controller="MyController">
    <button ng-click="add(1)">Add</button>
    <a href="#" ng-click="subtract(2)">Subtract</a>
    <h4>Current count: {{ counter }}</h4>
  </div>

  <script>
    var app = angular.module('myApp', []);
    app.controller('MyController', ['$scope', function($scope) {
      $scope.counter = 0;
      
      $scope.add = function(amount) { 
         $scope.counter += amount; 
      };
      $scope.subtract = function(amount) { 
         $scope.counter -= amount; 
      };
    }]);
  </script>

</body>
</html>

Click to view the demo

Note

The code above defined a controller named MyController. In MyController it defined two methods and one property. One method adds value to the property by one. The other method subtracts the property by two.

The value property is binded to the h4 while the two methods are called from a button and an anchor.

ng-click directive binds the click event to the method handler.





















Home »
  AngularJS »
    AngularJS Tutorial »




Introduction
Buildin Filters
Buildin Directives