1. Introduction to AngularJS Services
In AngularJS world, the services are singleton objects or functions that carry out specific tasks. It holds some business logic. Separation of concern is at the heart while designing an AngularJS application. Your controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulating it.
For that we must create singleton objects called services. AngularJS can manage these service objects. Wherever we want to use the service, we just have to specify its name and AngularJS auto-magically inject these objects (more on this later).
Thus service is a stateless object that contains some useful functions. These functions can be called from anywhere; Controllers, Directive, Filters etc. Thus we can divide our application in logical units. The business logic or logic to call HTTP url to fetch data from server can be put within a service object.
Putting business and other logic within services has many advantages. First it fulfills the principle of separation of concern or segregation of duties. Each component is responsible for its own work making application more manageable. Second this way each component can be more testable. AngularJS provides first class support for unit testing. Thus we can quickly write tests for our services making them robust and less error prone.
Consider above diagram. Here we divide our application in two controllers: 1. Profile and 2. Dashboard. Each of these controllers require certain user data from server. Thus instead of repeating the logic to fetch data from server in each controller, we create a User service which hides the complexity. AngularJS automatically inject User service in both Profile and Dashboard controller. Thus our application becomes for modular and testable.
2. AngularJS internal services
AngularJS internally provides many services that we can use in our application. $http
is one example (Note: All angularjs internal services starts with $ sign). There are other useful services such as $route
, $window
, $location
etc.
These services can be used within any Controller by just declaring them as dependencies. For example:
module.controller('FooController', function($http){
//...
});
module.controller('BarController', function($window){
//...
});
Code language: JavaScript (javascript)
3. AngularJS custom services
We can define our own custom services in angular js app and use them wherever required.
There are several ways to declare angularjs service within application. Following are two simple ways:
var module = angular.module('myapp', []);
module.service('userService', function(){
this.users = ['John', 'James', 'Jake'];
});
Code language: JavaScript (javascript)
or we can use factory method
module.factory('userService', function() {
var fac = {};
fac.users = ['John', 'James', 'Jake'];
return fac;
});
Code language: JavaScript (javascript)
Both of the ways of defining a service function/object are valid. We will shortly see the difference between factory()
and service()
method. For now just keep in mind that both these apis defines a singleton service object that can be used within any controller, filter, directive etc.
4. AngularJS Service vs Factory
AngularJS services as already seen earlier are singleton objects. These objects are application wide. Thus a service object once created can be used within any other services or controllers etc.
We saw there are two ways (actually four, but for sake of simplicity lets focus on 2 ways that are widely used) of defining an angularjs service. Using module.factory
and module.service
.
module.service( 'serviceName', function );
module.factory( 'factoryName', function );
Code language: JavaScript (javascript)
When declaring serviceName
as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService()
. This object instance becomes the service object that AngularJS registers and injects later to other services / controllers if required.
When declaring factoryName
as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.
In below example we define MyService
in two different ways. Note how in .service
we create service methods using this.methodname
. In .factory
we created a factory object and assigned the methods to it.
AngularJS .service
module.service('MyService', function() {
this.method1 = function() {
//..
}
this.method2 = function() {
//..
}
});
Code language: JavaScript (javascript)
AngularJS .factory
module.factory('MyService', function() {
var factory = {};
factory.method1 = function() {
//..
}
factory.method2 = function() {
//..
}
return factory;
});
Code language: JavaScript (javascript)
5. Injecting dependencies in services
Angularjs provides out of the box support for dependency management.
In general the wikipedia definition of dependency injection is:
Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time. …
We already saw in previous tutorials how to use angularjs dependency management and inject dependencies in controllers. We injected $scope
object in our controller class.
Dependency injection mainly reduces the tight coupling of code and create modular code that is more maintainable and testable. AngularJS services are the objects that can be injected in any other Angular construct (like controller, filter, directive etc). You can define a service which does certain tasks and inject it wherever you want. In that way you are sure your tested service code works without any glitch.
Like it is possible to inject service object into other angular constructs, you can also inject other objects into service object. One service might be dependence on another.
Let us consider an example where we use dependency injection between different services and controller. For this demo let us create a small calculator app that does two things: squares and cubes. We will create following entities in AngularJS:
- MathService – A simple custom angular service that has 4 methods: add, subtract, multiply and divide. We will only use multiply in our example.
- CalculatorService – A simple custom angular service that has 2 methods: square and cube. This service has dependency on MathService and it uses MathService.multiply method to do its work.
- CalculatorController – This is a simple controller that handler user interactions. For UI we have one textbox to take a number from user and two buttons; one to square another to multiply.
Below is the code:
5.1 The HTML
<div ng-app="app">
<div ng-controller="CalculatorController">
Enter a number:
<input type="number" ng-model="number" />
<button ng-click="doSquare()">X<sup>2</sup></button>
<button ng-click="doCube()">X<sup>3</sup></button>
<div>Answer: {{answer}}</div>
</div>
</div>
Code language: HTML, XML (xml)
5.2 The JavaScript
var app = angular.module('app', []);
app.service('MathService', function() {
this.add = function(a, b) { return a + b };
this.subtract = function(a, b) { return a - b };
this.multiply = function(a, b) { return a * b };
this.divide = function(a, b) { return a / b };
});
app.service('CalculatorService', function(MathService){
this.square = function(a) { return MathService.multiply(a,a); };
this.cube = function(a) { return MathService.multiply(a, MathService.multiply(a,a)); };
});
app.controller('CalculatorController', function($scope, CalculatorService) {
$scope.doSquare = function() {
$scope.answer = CalculatorService.square($scope.number);
}
$scope.doCube = function() {
$scope.answer = CalculatorService.cube($scope.number);
}
});
Code language: JavaScript (javascript)
Thus in the above angularjs injected service object to another service and in turn injected final service object to the controller object. You can inject same service object in multiple controllers. As angularjs service object is inheritedly singleton. Thus only one service object will be created per application.
6. End to End application using AngularJS Service
Let us apply the knowledge that we acquired so far and create a ContactManager application. This is the same app that we built-in our last tutorial. We will add a service to it and see how we can divide the code between service and controllers. Following are some basic requirements of this application:
- User can add new contact (name, email address and phone number)
- List of contacts should be shown
- User can delete any contact from contact list
- User can edit any contact from contact list
Following is the HTML code which defines a FORM to save new contact and edit contact. And also it defines a table where contacts can be viewed.
6.1 The HTML
<div ng-controller="ContactController">
<form>
<label>Name</label>
<input type="text" name="name" ng-model="newcontact.name"/>
<label>Email</label>
<input type="text" name="email" ng-model="newcontact.email"/>
<label>Phone</label>
<input type="text" name="phone" ng-model="newcontact.phone"/>
<br/>
<input type="hidden" ng-model="newcontact.id" />
<input type="button" value="Save" ng-click="saveContact()" />
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.phone }}</td>
<td>
<a href="#" ng-click="edit(contact.id)">edit</a> |
<a href="#" ng-click="delete(contact.id)">delete</a>
</td>
</tr>
</tbody>
</table>
</div>
Code language: HTML, XML (xml)
Next we add the AngularJS code to and life to our ContactManager application. We define a module ‘app’. This module is then used to create Service and Controller.
See in below code how ContactService
is created. It has simple methods to save/delete/get the contact.
Note how the service object in injected in controller.
6.2 The JavaScript
var module = angular.module('app', []);
module.service('ContactService', function () {
//to create unique contact id
var uid = 1;
//contacts array to hold list of all contacts
var contacts = [{
id: 0,
'name': 'Viral',
'email': '[email protected]',
'phone': '123-2343-44'
}];
//save method create a new contact if not already exists
//else update the existing object
this.save = function (contact) {
if (contact.id == null) {
//if this is new contact, add it in contacts array
contact.id = uid++;
contacts.push(contact);
} else {
//for existing contact, find this contact using id
//and update it.
for (i in contacts) {
if (contacts[i].id == contact.id) {
contacts[i] = contact;
}
}
}
}
//simply search contacts list for given id
//and returns the contact object if found
this.get = function (id) {
for (i in contacts) {
if (contacts[i].id == id) {
return contacts[i];
}
}
}
//iterate through contacts list and delete
//contact if found
this.delete = function (id) {
for (i in contacts) {
if (contacts[i].id == id) {
contacts.splice(i, 1);
}
}
}
//simply returns the contacts list
this.list = function () {
return contacts;
}
});
module.controller('ContactController', function ($scope, ContactService) {
$scope.contacts = ContactService.list();
$scope.saveContact = function () {
ContactService.save($scope.newcontact);
$scope.newcontact = {};
}
$scope.delete = function (id) {
ContactService.delete(id);
if ($scope.newcontact.id == id) $scope.newcontact = {};
}
$scope.edit = function (id) {
$scope.newcontact = angular.copy(ContactService.get(id));
}
})
Code language: PHP (php)
That’s All Folks
We saw that angularjs service/factory objects are. How to define our own custom service/factory object in angularjs. Also we saw how dependency injection works. In the end we created a simply calculator application that wrap up all the concepts.
I hope you liked this tutorial. Feel free to post your comment below.
In this ongoing series, I will try to publish more AngularJS articles on topics like angularjs $http service, AngularJS filters, AngularJS directives etc.
Some great articles you have posted! Any article that you can refer to display grid with AngularJS service? Thanks!
Hi that is great quick start tutorial for AngularJS
but tell me how i use that AngularJS to persist data in db
and also tell me how you secure business logic from user side in AngularJS
Sorry you cant. This is a client side app framework. Only things which are not too sensitive must be coded in angular. You have the rest of the logic in the server side.
Client side code can always be viewed in the devtools.
But you can still make it really tough to understand for the person looking at your code by obfuscating it. Thats all I know!
Why dont you use HTML5’s Local storage or the webSQL. Both are great.
Is there any particular reason not to pass the newcontact directly from the ng-click as a parameter of save()?
and
This seems to me to have better reusability and encapsulation. For example, you may want to be able to add a new contact from somewhere else without binding to the single input you already have.
Anyway, I am honestly curious if there is any particular “Angular” reason to do it the way you did.
Also, I realize you clear the $scope.newcontact var after saving… if you use the variation I suggested, you can still do that in the ng-click:
I personally consider it a good practice to write minimal code in HTML that’s why I support his approach.
This is a great tutorial to start with anulgar’s service & factory…
Thanks a lot for giving a sweet & small expample…
Hi Viral, Have been following your tutorials on AngularJS. The explanation is very crisp and clear. Please keep posting more tutorials in the future.
Hi dude this is excellent example.
HATS of U.
Thank you for making the tutorial.
One thing that seems to be missing, and was in fact the reason I read the tutorial, was an answer to the question of when to use a factory vs a service? Can you provide different use cases for when one would be preferable over the other? Seems like a factory could just as easily return a function, which would make it identical to a service (Is this correct).
Thank you for the awesome tutorial!
Hi Viral,
I am newbie to AngularJS and this article has helped me a lot in understanding concepts.
I am trying to code something like :- I have a dropdown and when I select one value, it should in turn open another drop down and if not, the second dropdown should not be displayed.
For ex. I have dropdown with values A, B, C and when I select C, I should see another select element with values in it. But when I select A or B, the second select is not visible. How can I achieve this?
Thanks in advance.
You should look at ng-if, ng-show and ng-hide.
These will allow you to control whether or not the second selection box displays by setting an expression on it, as follows…
…
ng-if will add the element to the dom model if the condition is true. This means if the expression is false, the element does not even exist, so be careful if referencing it from elsewhere.
ng-show will show the element only if the condition is true, hide when false. The element will always exist in the DOM.
ng-hide is the exact reverse of show. Shows when the expression is false, hide when true.
Happy Coding!
can you please post an example on using multiple filters with multiple input text boxes in angularjs
Yay, another over simplified tutorial that ignores the complexity of any real-world app. Try doing this example when the model data is requested asynchronously from the server. Then add another controller that needs to share data using the service. That would be a very simple and practical example, however the code required to achieve that is way more complex than you would imagine. And you could take it one step further, how about instead of having a save button like you would on a web page from 10 years ago, you handle data automatically being updated when an input changes.
I’m sorry, but I’ve been through a hundred tutorials just like this. Afterwards I feel like I can jump right in and create a simple app, until I add one more controller and deal with real data from a server, then all the sudden everything in these tutorials is irrelevant. Tutorials titled “Sharing data between controllers using services” will have an example with static data, one service, and one controller. Yes, I know you can create a service and inject that service into all of your controllers, but so what? That’s the least of the problems with sharing data between controllers. The real issue is how do you keep your data in sync between all of your services and controllers and the server, and what is the best way to handle the asynchronous nature of loading data into the application. Those are the practical real world scenarios that tutorials need to explain.
John Smith – you seem like the smartest guy in the room. You should stop reading so many dumb tutorials and start writing good ones.
Viral (or anyone) – One thing I don’t understand is where $scope.newcontact is declared or exposed on the controller? It’s used in the 3 functions on the controller – but it is not actually on the controller itself anywhere. Is this an oversight or am I missing something?
great tutorial…Thanks.
The newContact value is created in the $scope.edit(id) function defined in the controller. It is called when the user clicks the edit button on a particular contact. It is also created in the save() method, but only after the save has completed. It is also created in the delete method if the id in the newContact matches the passed id.
From just a brief review of the code, this looks like it could blow up for many reasons – trying to save before editing, deleting before editing.
It would be much better to declare the $scope.newContact variable and its initial structure in the controller than to hide its creation in various methods. You could even have a function in the service return the initial structure so it could be updated in a single place later.
Excellet Viralpatel. Thanks i have learned AngularJS in just one hour with your tutorial.
Nice Article Viral. Keep Posting. Thanks a lot.
This is one great tutorial… I am able to create my own Angular Service… in 15 mins…
GREAT JOB… Mr.VIRUS
Nice tutorial. Thanks for your time
Viral – just wanted to quickly compliment you on your articles – they are really well-done, and easy to understand. I very much appreciate the time you take to write up these AngularJS tutorials, and I hope you continue to write more of them!
” You can inject same service object in multiple controllers. As angularjs service object is inheritedly singleton. Thus only one service object will be created per application.”
THANK YOU! I couldn’t find this answer anywhere, ended up just testing it to see what happened.
This is a excellent tutorial to start with anulgar’s service & factory…and my hart full thanx for providing such a great tutorial.
Nice Tutorial
Excellent Tutorial. Very Simple.
The this.add = function(a, b) { return a + b }; should be
this.add = function(a, b) { return ( parseInt(a) + parseInt(b) ) } ..
Because + is having concatenation property By default
I’ve been surfing different explanations of the differences between service and factory for the last hour and this is by far the clearest and best explanation for an experienced classical OO developer.
Excellent work, it addressed my use case exactly. If I can make one suggestion, it would have been great if you had provided some unit tests to show how they can be set up.
Thanks alot, this is really a very good tutorial for the starter/beginner’s. Hope you will continue doing the same further…
Nice Tutorial. Thanks 4 the simplicity
I’m getting a cannot read property ‘id’ of undefined flagging on this line;
[if (contact.id == null)]
Any ideas?
Hey Brad, I am having the same issue. Let me know if you fix it. I’m going to continue working on it.
if (contact.id == null) can just be if (contact.id) as it would be evaluated as true or false. It works in my app.
hello sir, angularjs provide a two way data binding can i possible two use angularjs with servle,jsp & JDBC if u have any idea post it in ur blog thanks sir
You definitely can not use JDBC directly. To use it from angular, create a web service on the server that performs all the database work and returns its results as JSON. You can then call this service from within an Angular application by using the angular $http service.
The same thing goes for a servlet – since it is already on one or more URLs, you can call it from angular using the $http service.
Best practice would have you create an angular service which encapsulates the calls to these services.
You would then call the angular services from your angular controller and assign the results to $scope values. If you bind your UI objects to these scope values, changes to the UI controls will update the data, and vice versa. In order to save the data back to the database, use the $scope variables as parameters to the save() methods on your angular service.
If you use spring on your server side, spring can cast the JSON data from the client into a matching java object for further processing.
Viral its really nice article for angular js
Hi,
I’ve a question related to your service definition.
From this post: “…service is a stateless object that contains some useful functions”
Then, in the “Custom services” section you create services like this one:
module.service(‘userService’, function(){
this.users = [‘John’, ‘James’, ‘Jake’];
});
Is the previous service stateless? (taking into account that it contains a list of users…)
Thanks.
Very Useful
Some great articles you have posted! Any article that you can refer to display grid with AngularJS service? Thanks!
Great post. Really useful. Just a quick question, in “5. Injecting dependencies in services” why did you use services, rather than factories? Both would work, right? Just trying to understand why to use one not the other.
Great post. Can you add few more words which will explain a difference between “instance of a method” that service returns and “object with assigned methods” that factory returns relatively to a real world applications? For newbies please )
Excellent for beginners…Thanks a lot Viral ….Keep Posting……
hi viral can u please let me know . In last example how $scope.contact is updated automatically When I push contact in service contact object. I know we bind our $scope.contacts = ContactService.list(); . I am not clear how all the time(at the time of edit, delete ,add) our main $scope.contacts is updated . Is it updated (called) all time.
Please let me know.
Thanks in advance. and Keep posting..
Viral, this is a nice article. A good explanation on Service vs. Factory. In your example, it would be great if you tested for success or error on the return.
Really nice post. Got a very good introduction to services and factory
Really nice post. Got a very good introduction to services
Excellent!! Very useful, Thanks
I need a code to Add a title in the popup based on the type of the any document using angularjs.
thanks in advance.
Superb. Thanks For YOur Example.
Suoerbbbbb.. This work awesome. i complete angular services . and 50% chapter….
//Service code
var integrityService = angular.module(‘starter.IntegrityService’, []);
integrityService.service(‘IntegrityAuthService’, [‘configData’, function($http,’serverDetails’){
[/code javascript]
var appController = angular.module(‘starter.controllers’, []);
appController.controller(‘AppCtrl’,function($scope, $ionicModal, $timeout,$location,IntegrityAuthService) {
[/code javascript]
Getting below error
Error: [$injector:unpr] Unknown provider: IntegrityAuthServiceProvider <- IntegrityAuthService
http://errors.angularjs.org/1.2.17/$injector/unpr?p0=IntegrityAuthServiceProvider%20%3C-%20IntegrityAuthService
what could be its cause
Welcome to Spectrum Engineering Consortium LTD
Name
Email
Phone
Age
Name
Email
Phone
Age
Action
{{ contact.name }}
{{ contact.email }}
{{ contact.phone }}
{{ contact.age }}
edit |
delete
function myFunction() {
document.getElementById(val=””);
alert(“Shuld not be blank”);
}
var uid = 1;
function ContactController($scope) {
$scope.contacts = [
{ id:0, ‘name’: ‘Viral’,
’email’:’[email protected]’,
‘phone’: ‘123-2343-44′,’age’:’20’
}
];
$scope.saveContact = function() {
if($scope.newcontact.id == null) {
//if this is new contact, add it in contacts array
$scope.newcontact.id = uid++;
$scope.contacts.push($scope.newcontact);
} else {
//for existing contact, find this contact using id
//and update it.
for(i in $scope.contacts) {
if($scope.contacts[i].id == $scope.newcontact.id) {
$scope.contacts[i] = $scope.newcontact;
}
}
}
//clear the add contact form
$scope.newcontact = {};
}
$scope.delete = function(id) {
//search contact with given id and delete it
for(i in $scope.contacts) {
if($scope.contacts[i].id == id) {
$scope.contacts.splice(i,1);
$scope.newcontact = {};
}
}
}
$scope.edit = function(id) {
//search contact with given id and update it
for(i in $scope.contacts) {
if($scope.contacts[i].id == id) {
//we use angular.copy() method to create
//copy of original object
$scope.newcontact = angular.copy($scope.contacts[i]);
}
}
}
}
Great !
Wow super article
excellent article, it is very useful Us…………. Thanks a lot………………….
Hi viral,
Thanks for the explanation. I have a query . We are developing a web application using angular js where the menu is created based on the role of the user who logs in. Now post login this menu is going to be static and will be a part of header div. for such views also should we rely on $scope for menu data or can we add it to session storage etc. your input would really help.
Thanks
Nice article, but I’m still a bit confused.
I did a mistake in my app today, and then stumbled across your article.
I mixed the methods and my script worked fine:
I wanted what you explained to be a factory, but I used “service” instead.
I then swapped back service for factory, and everything seemed to work identically. Of course my factory is still a work in progress, but the content didn’t seem to make any difference on the controller side (simply using the reference, not instantiating the object).
I’m not sure I understood better, but I’ll try to stick the factory “syntax” but it seems more natural to me XD.
Arg, sorry, I realised that in my last sentence, my second “but” should have been “because” XD
Excellent work . Keep it up…God bless you for all your efforts in helping others learning the technology….
Thanks for the article. But can you please explain how do we do the same Calculator app using factory?
Thanks. I am able to do the same using factory.
it is very difficult understand for the people who starts beginners
Your tutorials on AngularJS helped me to startup with it (looking forward for more of this serie!). I wish they were included on the AngularJs website as they are very clear and easy to follow. Thanks!
Thanks Buddy for the great tutorial, it was very helpful for beginner like me.You have pointed the things in a very understandable manner.
it helped me, understandable
Thanks
Wonderful stuff! Was able to connect to SQL server db via express.js to serve up nice rest api and get some nice UI going
Thanks so much!!!
I am also trying to call a method of one service into the other service but it is giving error saying
Cannot read property ‘create’ of undefined
Please ignore syntax error if it is there
We needed an example of using a factory. Please work on your english. Thanks.
Thanks..Good article.
Thanks a million. Very well explained and easy to follow. Very much appreciated.
Well explained article ,thanks a lot for your blog.
Great example Viral, (and your English is just fine). Thank you.
One of the best tutorials I have used in a long time. Well done. Perhaps a little more info on pros and cons of factory\service approaches.
After seeing your tutorial I can started with AngularJS Project. THANKS………..
it was very helpful. thanks
Thanks so much! I can see how service and factory work and how they connect with controller
Thanks for the tutorial..
the simplified way in which you explained the concepts is commendable
Very good Example and Easy to Under stand for Every one. Thanks Lot
is there any way to create multiple instances of a factory in another factory ?
//factory 1
module.factory(‘MyService’, function() {
});
//factory2
module.factory(‘MyService1’, [ ‘MyService’ , function( MyService) {
var obj = new MyService();
}]);
is there any way to create multiple instances of a factory in another factory ?
//factory 1
module.factory(‘MyService’, function() {
});
//factory2
module.factory(‘MyService1′, [ ‘MyService’ , function( MyService) {
var obj = new MyService();
}]);
This was an incredibly well-written and informative tutorial. Thanks for sharing your wealth of knowledge. This really clarified things for me. Cheers again!
Thank you so much. This article helped me a lot in understanding AngularJS. This is very easy to follow.
Awesome article !!
Welldone…Excellent Explanation…Keep the good work…
Thank you very much….great tutorial
nice article
Excellent tutorial. This is very clear and the example using the service approach works nicely! Thanks for posting it. You should help on the next O’Reilly Angular book. They could use it :-)
Section one, last sentence, “Thus our application becomes for modular and testable.” I think you meant to write more, not for.
Thanks,
Grammar Guy
Section one, third paragraph, first sentence. “Thus service is a stateless object that contains some useful functions.” I think you meant to write The, not Thus…
Nice tutorial, Good job…… Thnx
Thank you. It’s easy to follow.
Very good tutorial really even for beginners also it’s very easy to understand not only this post for Java, JQuery,spring i am getting good knowledge from this site….Thank you so much viral
Its great tutorial for beginner!!! Thank you a lot!!!
Thanks a lot, this was very informative about controllers and services. Well done.
Very simple way to explain. I cleared my concepts using your articles & examples.
Can you please add custom directive tutorial?
Thnx
Chandra
Great article, much easier to follow than a lot on the web – at last an article that KISS!
This was lucid. Thanks for taking time to write this.
Thanks Viral, for the excellent tutorial, it’s very easy to understand & to practice the tutorials these were really helpful, waiting to see the new interesting topics on Angular JS.
Thanks,
Sandeep.
Thanks Viral, excellent tutorial, nice flow, easy to understand.
Awesome tutorial with examples, even a biginners can follow these and get into knowledge of subject easily.
Thanks a lot
Thanks Viral, Please send a post on AngularJS with RESTful web services.
An excellent tutorial. Thank you so much. By the way, could you please tell me whether it can read a json from an URL instead of directly initialize in the service.js file? (For example, you have written //contacts array to hold list of all contacts
var contacts = [{
id: 0,
‘name’: ‘Viral’,
’email’: ‘[email protected]’,
‘phone’: ‘123-2343-44’
}];
and I want to read dynamic data from an URL)
Thanks.
Thanks this blogentry.I understood how to be use service , controller together .. thank you again
Nice job buddie, Thanks a lot.
nice guide,
But you dont explain much on the main question, when should i use Service, and when we should Factory
Nice explanation of service and factory I was struggling a lot now you made me clear. Thank you so much………. :)
Clearrd many doubts regarding angular.
Thanks buddy (y)
This is classic, you explained with serenity .
Thanks Guru!
Good article. One thing not clear to me that when to use service and when to use factory?
Thanks, nice post
very nice for angularjs learner
thank you very much
please help me how to create controller and service in project
if i have more than one function at the time like save , edit , dropdown , then how to define service in service page
please help me
i am learner for angularjs
i hope , you help me soon
Many thanks brother.
thank you a lot, very to the point, no fuss and effective tutorial.
Really Awesome Article.. Patel Bhai….I have started learning Angular.. ..Good One..
Please……………..
create a tutorial on node.js.
I am impressed with your tutorial
Very nicely explained.. i got a clear picture of services . With you permission i would like to answer the question most of them asking .
Factory vs Service : If we need an object in return use Factory … if we need a function or object use Service .
Please correct me if i am wrong.
thanks so much. was great article!! waiting for more!
Great Tutorial thank for the help in understanding AugularJS.
It is nice article, very useful for beginners…..
Very useful. Thank you.
Thank you very much, this blog help me to clearly understand angular js. Realy nice blog
nice tutorial ..thank you
I don’t understand exactly how contacts-variable in the scope get updated? When I save something it pushes the new object to service’s contacts array but how these changes are updated in $scope?
Dear Vivvv!
First please check the html form’s hidden id and then keep focus on save function.It has a very clear logic.
Good One.
ViralPatel – I really appreciate you for having given clear explanations with neat examples and code. I have never seen it in any other sites. Please continue the great job – your examples are great and works perfect
Thanks, very clear!
Thank you very much! Great tutorial!
hello world
God bless You. This tutorial rocks.
This is really helpful. Clean and very easy to understand. Thanks a ton…… :)
Really Awesome Article…
Great…
Thanks. A concrete tutorial. Just to the point
Very impressive tutorial – absolutely to the point with real world application, well done!!
Its what the actual post. I got to work with services now. Thanks.
Hello,
Really nice article I have a question,
Can service object be injected in multiple controller’s spread across many different .js files and be used to call service methods for calculations ?????? I tried actually and failed to do so, thats why asking.
Its really good. Thanks for your article. Please update services using $resource
This is excellent. It is very clear to understand what is service and what is factory with simple examples. I appreciate.
Thank you . Great article
Excellent Article. Nicely written and well explained. Thanks.!
Excellent and the great and then great and very great and super great article ! It clearly defines the differnence between Service and Factory, and easy way to understand AngularJs.
This is a great article for a beginner like me. But I have one question. What if the SAVE button is changed to SUBMIT button. The reason being I can also enter filter information in the top portion of the form that should in essence restrict the list portion at the bottom. Can u please explain how we do this. This would be of great help.
Thanks
Also I forgot to mention. How to link this to the back end REST service that provides data. How to transfer the search data back to the client side?
Excellent
Nice job!
Really this one is a clear stuff.
Great tutorials! I enjoyed reading them.
Thank you :)
Perfect. Simple and clear.
Thanks bro
When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService(). This object instance becomes the service object that AngularJS registers and injects later to other services / controllers if required.
When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.
can you make it little bit simple it is same like http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory
Thank very much, you put off my headache.
Thanck, nice lesson!!!
This is a excellent tutorial to start with anulgar’s service & factory…and my hart full thank you for providing such a great tutorial. it’s a very nice tutorial for beginners……
Excellent explaination, you are superb.
great work
Such a concise and excellent tutorial! I appreciate the time you’ve put into this :)
Thanks for this article. The way you explained the topic is really good and the examples were also helpful!
Thank you too much
Really great, clear tutorial. Thanks for taking the time to put this together, and also adding two examples. Keep up the good work.
its helpfull..
Great tutorial. Thx a lot
Nice Article.
How to transfer the search data back to the client-side?
good
I need to create 3 views along with 3 controllers and views are going to load via controller. Could you suggest me how many ways are there to load the views.
AngularJS Service / Factory : To keep it simple, use the $http module (see $http vs $resource). This has also the advantage that $http returns a promise which you should be able to use as follows (adapted from delaying-controller-initialization).
Alternatively, if the two controllers are on the same route and one is contained in the other, it may be easier to access the parent controller’s scope with $scope.$parent.data.
function tricoreContrller($scope, data) {
$scope.users = data;
}
function webdevController($scope, data) {
$scope.users = data;
}
var resolveFn = {
data : function($http) {
return $http({
method: ‘GET’,
url: ‘http://server/getJSON’
});
}
};
tricoreContrller.resolve = resolveFn;
webdevController.resolve = resolveFn;
var myApp = angular.module(‘myApp’, [], function($routeProvider) {
$routeProvider.when(‘/’, {
templateUrl: ‘/editor-tpl.html’,
controller: tricoreContrller,
resolve: tricoreContrller.resolve
});
// same for the other route for webdevController
});
This is awesome beginners guide to AngularJS. Thank you!
Great information. Since last week, I am gathering details about the AngularJS experience.
There are some amazing details on your blog which I didn’t know. Thanks.
Can anyone solve the above square and cube root example using angularjs providers?