Create Your Own Service in AngularJS


Use a Custom Service Inside a Filter. Once you have created a service, and connected it to your application, you can use the service in any controller, directive, filter, or even inside other services

To create your own service, connect your service to the module.
create service called "hello"
var app = angular.module("myApp", []);
app.service('hello', function() {
	this.add = function (x,y) {
		return "Hi "+x+y+ " , Welcome to DataStapler.com";
	}
});

To use your custom made service, add it as a dependency when defining the filter:

Use the custom made service named hello to say Hi and welcome to DataStapler.com
app.controller('myCtrl', function($scope, hello) {		
	$scope.ad = function(x,y) { return hello.add(x,y)}
});
Display that name at UI
{{ad(fname,lname)}}
Total program
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>

		<div ng-app="myApp" ng-controller="myCtrl">

			Enter First Name: <input type="text" ng-model="fname"><br>
			Enter Last Name: <input type="text" ng-model="lname"><br>
			
			<br>
			<input type="checkbox" ng-model="c">
			<h1 ng-show="c">{{ad(fname,lname)}}</h1>

		</div>

		<script>
			var app = angular.module("myApp", []);
			app.service('hello', function() {
				this.add = function (x,y) {
					return "Hi "+x+" "+y+ " , Welcome to Data Stapler";
				}
			});

			app.controller('myCtrl', function($scope, hello) {				
				$scope.ad = function(x,y) { return hello.add(x,y)}
			});
		</script>

     </body>
</html>

Enter the first name and second name, just click on select box. Now you can welcome message using custom service.

AngularJs Custom service