AngularJS Services.

In the previous tutorials, I did not use the Services pattern of AngularJS. In this post, I would just replace some code with the use of Services.

Here goes the index.app.js

var indexApp = angular.module("indexApp", []);

indexApp.service('PostService', function($http)
{

	// Load posts.
	this.loadPosts = function(onLoadComplete)
	{
		$http.get('post/list').success(function(data)
		{
			onLoadComplete(data);
		});
	};

	// Post data.
	this.savePost = function(formData, onSaved)
	{
		$http.post('post/save', formData).success(function(data)
		{
			onSaved(data);
		});

	};
	
	// Delete.
	this.deletePost=function(id,onDelete)
	{
		$http.delete('post/remove/' + id).success(function(data)
				{
			onDelete(data);
				});
	
	};

});
indexApp.controller('index.controller', function($scope, PostService)
{
	PostService.loadPosts(function(data)
	{
		$scope.posts = data;
	});

	$scope.doSubmit = function()
	{
		var formData = {
			scrap : $scope.form.scrap
		};

		PostService.savePost(formData, function(data)
		{
			$scope.posts = data;
		});
	};
	// Delete.
	$scope.doDelete=function(id)
	{
		PostService.deletePost(id,function(data)
				{
			$scope.posts = data;
				});
	};
});

In this code, I created a service called PostService, and put some code to load,save and delete scraps. In every method, I just put a callback function so that when the operation is completed, I can perform the necessary actions in the controller. Just simple code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s