AngularJS service

AngularJS services and factories are singletons and also should not reference the DOM.

Do not inject one service into another because you are making them tightly coupled. Inject services into the controllers.

AngularJS factory example:

html:

<section ng-app="app" class="container">
    <section ng-controller="appCtrl">
        <h3>List of countries</h3>
        <ul>
            <li ng-repeat="country in srvc.countriesList">
                {{country.name}} - {{country.capital}}
            </li>
        </ul>
 
        <h3>Add new country</h3>
        <p>Name:
            <input type="text" ng-model="newCountry.name" />
        </p>
        <p>Capital:
            <input type="text" ng-model="newCountry.capital" />
        </p>
        <p>
            <button ng-click="addCountry()">Add new country to the list</button>
        </p>
    </section>
</section>

app.js:

var app = angular.module('app', []);
 
app.factory('appSrvc', function () {
    return {
        // can use $http object to retrieve data in a "real" app
        countriesList: [{
            name: 'England',
            capital: 'London'
        }, {
            name: 'Germany',
            capital: 'Berlin'
        }, {
            name: 'Italy',
            capital: 'Rome'
        }, {
            name: 'Spain',
            capital: 'Madrid'
        }]
    };
});
 
app.controller('appCtrl', function ($scope, appSrvc) {
    $scope.srvc = appSrvc; // bind scope variable to service
 
    $scope.addCountry = function () {
        $scope.srvc.countriesList.push({
            name: $scope.newCountry.name,
            capital: $scope.newCountry.capital
        });
        $scope.newCountry = {}; // clean form
    }
});

Leave a Reply

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