Book Image

Data Oriented Development with Angularjs

Book Image

Data Oriented Development with Angularjs

Overview of this book

Table of Contents (17 chapters)
Data-oriented Development with AngularJS
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Difference between a factory and a service


Factories and services are used almost interchangeably in Angular, however there is a subtle but important difference between the two. So let's see their usage and it'll be amply clear when and how to use each one. First let's use the service command:

app.service('myService', function(){
    this.hello = function() {
        return "Hello World";
    };
});

(Chapter6\example-app\fact-svc\my.svc.js)

myService has a single function called hello which returns "Hello World" when called. Now let's use the factory command:

app.factory('myFactory', function(){
    return {
        hello: function() {
            return "Hello World";
        }
   
	}
});

(Chapter6\example-app\fact-svc\my.fctry.js)

myFactory has a single function called hello which returns "Hello World" when called as well. So what's the difference? For that, let's look at a factory which can accept or maintain some state as shown in the following code:

app.factory('myFactoryWithState', function...