Book Image

AngularJS Web Application Development Blueprints

By : Vinci J Rufus
Book Image

AngularJS Web Application Development Blueprints

By: Vinci J Rufus

Overview of this book

If you are a web application developer interested in using AngularJS for a real-life project, then this book is for you. As a prerequisite, knowledge of JavaScript and HTML is expected, and a working knowledge of AngularJS is preferred.
Table of Contents (12 chapters)
11
Index

Writing your first factory service


As we learned earlier, a factory is written to return a single object, array, or function that can then be passed as a parameter to any other function or controller, across the entire application.

Let's create a factory function to store a country list and pass it on to our models via the controller.

Let's open the app/js/services.js file and add the following code:

'use strict';
angular.module('myApp.services', []).
value('version', '0.1')

.factory('rtmFactory', function() {
    var countries = [
    {name: 'USA',code: 'us'}, 
    {name: 'UK',code: 'uk'}, 
    {name: 'France',code: 'fr'}
    ];
    return {
        getCountries: function() {
            return countries;
        }
    }
})

Here, we are creating a factory named rtmFactory and chaining it to the myApp module.

Tip

Don't forget to remove the semicolon after the line, value ('version', '0.1'), so that the factory can be chained to it.

Within this factory, we will create an object to store the list...