Create AngularJS service example

Create AngularJS service example

This demo will show you how to create AngularJS service and call it from AngularJS controller also modify service data on button click:

  • HTML page:
<!DOCTYPE html>
<html data-ng-app="serviceModule">
<head>
<meta charset="ISO-8859-1">
<title>AngularJS Service example</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript">

	var serviceModule = angular.module('serviceModule', []);
	
	serviceModule.controller('myServiceController', function($scope, sampleService) {
	    $scope.users = sampleService.getUserData();
	    
	    $scope.modifyUsersData = function() {
	        $scope.users[0].firstName = 'Java2'
	        $scope.users[0].lastName = 'Honk2'
        	$scope.users[1].firstName = 'Alan2'
   	        $scope.users[1].lastName = 'Lee2'
	        $scope.users[2].firstName = 'Tom2'
	    	$scope.users[2].lastName = 'Nally2'
	    };
	
	});
	
	serviceModule.service('sampleService', function() {
	    return {
	        getUserData: function() {
	            return [
	                { firstName: 'Java', lastName: 'Honk'},
	                { firstName: 'Alan', lastName: 'Lee'},
	                { firstName: 'Tom', lastName: 'Nally'}
	            ];
	        }		    
	    };
	});
	
</script>
</head>
<body data-ng-controller="myServiceController"> 
	
	<button data-ng-click="modifyUsersData()">Modify Users Data</button>
	<div data-ng-repeat="user in users">User Name: {{user.firstName}} {{user.lastName}}</div>	

</body>
</html>

Output:

Create AngularJS service example

Run this code in jsfiddle here

Leave a Reply

Your email address will not be published. Required fields are marked *