angular.bind


angular.bind function โ€“ It basically returns a function(fn) which is bound to itself. You can also supply optional arguments that are prebound to the function.
Here is this tutorial we are going to explain how to use the angular.bind function with example and online demo.


angular.bind Function Example

Syntax

Syntax for the angular.bind is given below โ€“

Syntax:

angular.bind(self, fn, args);

Arguments

  • self โ€“ In which context fn(function) should be evaluated.
  • fn โ€“ Function to be bound.
  • argsโ€“ Optional arguments to be prebound to the fn function call.

Here is simple example of angular bind. In this example angular bind is used to bind the add function and the arguments โ€“ $scope.input1, $scope.input2 will be passed to the add function. The below example accepts two arguments and returns their addition โ€“

angular.bind function example :

<!DOCTYPE html>
<html lang="en">
<head>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
 <script>
var myApp = angular.module("myApp", []);
 myApp.controller("myController", function($scope) {

 function add(a, b) {
           return parseInt(a)+parseInt(b);
        }
        $scope.getResult = function () {
            var result = angular.bind(this, add);
            $scope.result = result($scope.input1, $scope.input2);
        }
});
</script>
</head>
<body>  
<div ng-app="myApp">  
<div ng-controller="myController"> 
 
 Enter a number 1.
 <input type="text" name="addExample1" ng-model="input1"><br>
 Enter a number 2
 <input type="text" name="addExample2" ng-keyup="getResult()" ng-model="input2">
 <br>number 1 + number 2 = {{result}}<br>

</div> 
</div>
</body>  
</html>      

Try it ยป

If you run the above example it will produce output something like this โ€“


Advertisements

Add Comment

๐Ÿ“– Read More