- AngularJS provides factory() method to create factory object that can be reused across application.
- A factory object can be injected to any module in AngularJS application.
- In this Demo, "We will create factory object called with some method and inject this object to a controller".
- Below code uses factory() method to create StringUtil object.It has 2 methods getReverseString() for reversing the input string and getCharacterCount() for return the length of the input string.
<!DOCTYPE html> <html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="MyController">
<h3>Original String : {{originalString}}</h3>
<h3>Reverse String : {{reverseString}}</h3>
<h3>Character Count : {{characterCount}}</h3>
<script>
var myApp = angular.module("myApp", []);
myApp.factory("StringUtil", function() {
return {
getReverseString: function(inputString) {
return inputString.split("").reverse().join("");
},
getCharacterCount: function(inputString) {
return inputString.length;
}
};
});
myApp.controller("MyController", ["$scope", "StringUtil", function($scope, StringUtil) {
$scope.originalString = "Sandeep Kumar Patel";
$scope.reverseString = StringUtil.getReverseString($scope.originalString);
$scope.characterCount = StringUtil.getCharacterCount($scope.originalString);
}]);
</script>
</body>
</html>
- The output of the above code is embedded in below JSBIN link.