Wednesday, February 19, 2014

angular.identity example

Here is a simple use of angular.identity example, angular.identity helps to write functional style code.below is the documentation:

API Doc for angular.identity

As to showcase the use of this, here we have a simple angular application which displays square value and multiplied by 2 value of a number. For example:

Input Value:5
Square:25
Multiply By two: 10

To achieve this,  I have created two functions:

$scope.square = function (n) {
  return n * n
};

$scope.multplybyTwo = function (n) {
  return n * 2};

In addition to this, I have a separate helper function which calls these function passing it's first argument.

$scope.givemeResult = function (fn, val) {
  return (fn || angular.identity)(val);
};

Then  the givemeResult function may be invoked in the below fashion:

$scope.initVal = 5;
$scope.squareResult = $scope.givemeResult($scope.square, $scope.initVal);
$scope.intoTwo = $scope.givemeResult($scope.multplybyTwo, $scope.initVal);


You may visit the Plnkr.

1 comment:
Write comments
  1. it is nice example. easy to understand angular.identity.

    ReplyDelete