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:


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


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 () {
            name: $,
            capital: $
        $scope.newCountry = {}; // clean form

Leave a Reply

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