AngularJS Controllers

AngularJS Controllers

AngularJS Controllers contains business logic for a single view through passing the injectable parameter  $scope in constructor function. Controller is attached to DOM via ng-controller directive. When controller is attached, we can add the behavior to $scope object by adding the functions. We can access all the properties of $scope objects in view model template, which is initiated in controllers.

Creating AngularJS Controller.

Controllers are just like classes or constructor functions that are responsible for providing the application behavior that supports the declarative markup in the template. The recommended way of declaring controllers is using the array notation. It is also called as Dependency Injection (DI).

Example

/*
app.js
using controller, JSON and DI example.
*/
'use strict';

// creating new module
angular.module('myApp', [])

//            controller      DI (dependency injection) array notation
//              |              |
//              ˅              ˅
.controller('productCtrl', ['$scope', function($scope) {
  // JSON data in scope object
  $scope.products = [
                      {name: 'Apple', price: 14.50, qty: 0},
                      {name: 'Orange', price: 10.25, qty: 0},
                      {name: 'Banana', price: 8.10, qty: 0}
                    ]
}]);
<!DOCTYPE html>
<!--
products.html
using ng-controller, ng-repeat, ng-model directives.
-->
<html ng-app="myApp">
<head>
  <!-- bootstrap CDN -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

  <!-- AngularJS CDN -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <script src="app.js"></script>
</head>
<body>
  <!--  ngController directive -->
  <!--       |                 -->
  <!--       ˅                 -->
  <div ng-controller="productController">
    <table class="table table-striped table-bordered">
      <tr>
        <th>Name</th>
        <th>Rate</th>
        <th>Qty</th>
        <th>Amount</th>
      </tr>
      <!-- ngRepeat directive -->
      <!--    |               -->
      <!--    ˅               -->
      <tr ng-repeat="product in products">
        <td>{{product.name}}</td>
        <td>{{product.price}}</td>
        <!--                     ngModel directive -->
        <!--                        |              -->
        <!--                        ˅              -->
        <td><input type="number" ng-model="product.qty" min="0" required></td>
        <!--           expression for calculating amount -->
        <td><strong>{{product.price * product.qty | currency}}</strong></td>
      </tr>
    </table>
  </div>
</body>
</html>
Name Qty Rate Amount
{{product.name}} {{product.price | number:2}} {{product.price * product.qty | currency}}

Accessing other Controller's function through $broadcast

We can access controller's functions through $broadcast object with passing function name and its arguments. It is mainly used when you are developing custom angular module, directive or UI Widget for re-usable common purpose. Through $broadcast method user can access your custom module's functions.

$rootScope.$broadcast(name, args);

Example

/*
app.js
using $rootScope, $broadcast and $on.
indexOf(), push() and splice() are JavaScript string functions.
*/
'use strict';

// creating new module
angular.module('myApp', [])

//            controller           rootScope
//              |                     |
//              ˅                     ˅
.controller('productController', ['$rootScope', '$scope', function($rootScope, $scope) {
  // JSON data in scope object
  $scope.products = [
                      {name: 'Apple', price: 14.50},
                      {name: 'Orange', price: 10.25},
                      {name: 'Banana', price: 8.10}
                    ];

  $scope.addtoCart = function(item) {
    // broadcast
    $rootScope.$broadcast('addItem', {'item':item});
  };

  $scope.removefromCart = function(item) {
    // broadcast
    $rootScope.$broadcast('removeItem', {'item':item});
  };
}])

// cart controller
.controller('cartCtrl', ['$scope', function($scope) {
  // event listener for broadcast object
  $scope.$on('addItem', function(event, args) {
    $scope.addItem(args.item);
  });

  // event listener for broadcast object
  $scope.$on('removeItem', function(event, args) {
    $scope.removeItem(args.item);
  });

  $scope.cartItems = [];

  $scope.addItem = function(item) {
    if ($scope.cartItems.indexOf(item) == -1) {
      $scope.cartItems.push(item)
      $scope.cartItems[$scope.cartItems.indexOf(item)].qty = 1;
    }
    else {
      $scope.cartItems[$scope.cartItems.indexOf(item)].qty += 1;
    }
  };

  $scope.removeItem = function(item) {
    var index = $scope.cartItems.indexOf(item);
    $scope.cartItems.splice(index, 1);
  };
}]);
<!DOCTYPE html>
<!--
product.html
broadcast object example
using ng-click, ng-show and ng-hide directive.
-->
<html ng-app="myApp">
<head>
  <!-- bootsrap CDN -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

  <!-- AngularJS CDN -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <script src="app.js"></script>
</head>
<body>
  <div ng-controller="productController">
    <table class="table table-striped table-bordered">
      <tr>
        <th>Name</th>
        <th>Rate</th>
        <th></th>
        <th></th>
      </tr>
      <tr ng-repeat="product in products">
        <td>{{product.name}}</td>
        <td>{{product.price | number:2}}</td>
        <td>
           <input type="button" class="btn btn-success" value="Add to Cart" ng-click="addtoCart(product)">
        </td>
        <td>
           <input type="button" class="btn btn-danger" value="Remove" ng-click="removefromCart(product)">
        </td>
      </tr>
    </table>
  </div>

  <!-- cart -->
  <div style="background-color: rgb(252, 249, 192); padding: 15px;">
    <h2><i class="fa fa-shopping-cart"></i> Cart</h2>
    <div ng-controller="cartCtrl">
      <label ng-hide="cartItems.length">Cart is Empty</label>
      <table class="table table-responsive" ng-show="cartItems.length">
        <tr>
          <th>Name</th>
          <th>Rate</th>
          <th>Qty</th>
          <th>Amount</th>
        </tr>
        <tr ng-repeat="cartItem in cartItems">
          <td>{{cartItem.name}}</td>
          <td>{{cartItem.price | number:2}}</td>
          <td>{{cartItem.qty}}</td>
          <td>{{cartItem.price * cartItem.qty | currency}}</td>
        </tr>
      </table>
    </div>
  </div>
</body>
</html>
Name Rate
{{product.name}} {{product.price | number:2}}

Cart

Name Rate Qty Amount
{{cartItem.name}} {{cartItem.price | number:2}} {{cartItem.qty}} {{cartItem.price * cartItem.qty | currency}}