AngularJS Custom Services
AngularJS allow to create Custom Services.There are two ways to create a service
By this method , we have to define service first and then assign method in it.
factory method
By this method , we have to define factory first and then assign method in it.
AngularJS allow to create Custom Services.There are two ways to create a service
- service method
- factory method
By this method , we have to define service first and then assign method in it.
return
factory;
});
app.service('myServices',
function
($http)
{
this.factorial
= function
(num)
{
var
rval = 1;
for
(var
i = 2; i <= num; i++)
rval
= rval * i;
return
rval
}
});
factory method
By this method , we have to define factory first and then assign method in it.
app.factory('myServices',
function
()
{
var
factory = {};
factory.factorial
= function
(num) {
var
rval = 1;
for
(var
i = 2; i <= num; i++)
rval
= rval * i;
return
rval
}
Example of Service method
<!DOCTYPE
>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<script>
var
app = angular.module("myApp",
[]);
app.service('myServices',
function
($http)
{
this.factorial
= function
(num)
{
var
rval = 1;
for
(var
i = 2; i <= num; i++)
rval
= rval * i;
return
rval
}
});
app.controller("myCtroller",
function
($scope, myServices)
{
$scope.DoPart
= function
()
{
$scope.getresult
= myServices.factorial($scope.DelIndex);
}
});
</script>
<div
ng-app="myApp"
ng-controller="myCtroller"
>
Factorial
Calculation
<input
type="text"
ng-model="DelIndex">
<button
type="button"
ng-click="DoPart($scope.DelIndex)">
Click
Me to </button>
Result
: {{getresult }}
</div>
Example of factory method
<!DOCTYPE
>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<script>
var
app = angular.module("myApp",
[]);
app.factory('myServices',
function
()
{
var
factory = {};
factory.factorial
= function
(num) {
var
rval = 1;
for
(var
i = 2; i <= num; i++)
rval
= rval * i;
return
rval
}
return
factory;
});
app.controller("myCtroller",
function
($scope, myServices)
{
$scope.DoPart
= function
() {
$scope.getresult
= myServices.factorial($scope.DelIndex);
}
});
</script>
<div
ng-app="myApp"
ng-controller="myCtroller"
>
Factorial
Calculation
<input
type="text"
ng-model="DelIndex">
<button
type="button"
ng-click="DoPart($scope.DelIndex)">
Click
Me to </button>
Result
: {{getresult }}
</div>
No comments:
Post a Comment