Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted February 12th, 2016
AngularJS Factories and Services

AngularJS is a powerful framework for JavaScript to make single page applications. I followed some tutorials because I wanted to know more about AngularJS. Most of the tutorials are very clear, but one thing was still confusing me and that was what is the difference between a service and factory.

What is a Service?

Okay, so what is a service? A service is like a singleton, angular is an MVC framework and as you already know angular has (m)odels, (v)iews and (c)ontrollers. Services are like models you can store data inside of variables and get or set the data through functions. Below you see an example how you declare a service in angular.

(function () {
    angular
        .module('myApp')
        .service('myService', function (
            //Your dependencies
        ) {
            //The service code
        });
})();

As you can see we use the service function from angular to declare a service. We give it 2 parameters the first one is the service name ‘myService’ the second parameter is a callback function. I don’t want to go in depth what a callback function is read more about JavaScript when you have questions.

Service dependencies and function declaration

What you have to understand is that the parameters we declare in the callback function are used as dependencies. Dependencies are mostly other factories or services in your application that you want to use inside of this service. Below you can see an example of how to use a dependencie in your service and how you declare your functions.

(function () {
    angular
        .module('myApp')
        .service('myService', function (
            //Your dependencies
        ) {
            //Below we declare the sayHello function
            this.sayHello = function (){
                console.log("HELLO WORLD!");
            }
        })
        .service('mySecondService', function (
            myService
        ) {
            this.sayHello = function () {
                //Calling a function from a dependencie
                myService.sayHello();
            };
        });
})();

How to use your services inside a controller or directive

Services are most of the time used inside controllers and directives. You want to have access to some services when you set data on the scope. Below you can see two examples.

Controller

(function () {
    angular
        .module('myApp')
        .service('myService', function (
            //Your dependencies
        ) {
            //Below we declare the function
            this.getWelcomeMessage = function (){
                return "Hello world!";
            }
        })
        .controller('myController', function (
            $scope,
            myService
        ) {
            $scope.welcomeMessage = myService.getWelcomeMessage();
        });
})();

Directive

(function () {
    angular
        .module('myApp')
        .service('myService', function (
            //Your dependencies
        ) {
            //Below we declare the function
            this.getWelcomeMessage = function (){
                return "Hello world!";
            }
        })
        .directive('myDirctive', function (
            myService
        ) {
            return {
                template: '<a>{{welcomeMessage}}</a>',
                link: function (scope) {
                    scope.welcomeMessage = myService.getWelcomeMessage();
                }
            };
        });
})();

What is a factory

A factory is almost the same as a service. Why do they both exist if they can accomplish the same thing? A factory offers slightly more flexibility than a service. Essentially, factories are functions that return the object, while services are constructor functions of the object. Here is an example of a factory.

angular
    .module('myApp')
    .factory('myService', function(
        //dependencies
    ) {
    //returning the object
    return {
        someFunction: function() {}
    };
});

As I told you before a factory offers slightly more flexibility than a service. I’ll show you an example about what you can do with a factory that you can’t do with a service. In this example I use ngResources and I do only return a function that returns a ngResources object. This isn’t possible in a service because services are constructor functions of the object.

(function () {
    angular
        .module('myApp')
        .factory('myService', function (
            //Injecting the $resource provider
            $resource
        ) {
            //Returning the object we get from the $resource provider
            return $resource ('http://www.exampleurl.com/api/:ID', {
                ID: 'example '
            }, {
                delete: { method: 'DELETE', isArray: true },
                get: { method: 'GET', isArray: true },
                post: { method: 'POST', isArray: true },
                put: { method: 'PUT', isArray: true }
            })
        });
})();

Posted by Ian Gerrebrands

Leave a Reply

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