1. Reusable, Single Responsibility. Dependency Injection ,Testable    (SOLID)
    2. Just local not network service
    3. Registered with Angular so that Angular can inject it
    4. Ex.

                                                    i.     Create service, factory call register it to Angular as name “eventData”.

eventsApp.factory(‘eventData’,function(){

     return{ event:{name:’abc’,date:’1/1/2014’}

     };

})

                                                   ii.     Inject the service in controller

eventsApp.controller('EventController',

    function EventController($scope, eventData) {

                   $scope.sortorder = 'name';

        $scope.event = eventData.getEvent();

 

                                                  iii.     Ajax call in service

eventsApp.factory(‘eventData’,function($http,$log){

     return{ getEvent:function(successed){

       $http({method:’GET’,url:’/data/event/1’}) // it is a valid http url will return json

            .success(function(data,status,headers,config)

{

$log.info(data,status,headers(),config);

    successed(data);

}).

Error(function(data.status.headers.config){

$log.warn(data,status,headers(),config);

});

}

     };

})

 

//in controller

eventData.getEvent(function(event){ $scope.event=event;});

 

                                                  iv.     Promise library $q

eventsApp.factory(‘eventData’,function($http,$q){

     return{ getEvent:function(){

                     var deferred=$q.defer();

 

       $http({method:’GET’,url:’/data/event/1’}) // it is a valid http url will return json

            .success(function(data,status,headers,config)

{

deferred.resolve(data);

}).

error(function(data.status.headers.config){

                                  deferred.reject(status);

});

}

return deferred.promise;

     };

})

//in controller

$scope.event = eventData.getEvent()  //promise will be auto bind, access event by $scope.event is not best practice, use it pass back from view.

Or

$scope.event.then(function(event){ console.log(event);},function(status) { console.log(status);});

 

                                                   v.     $resource service, build for access REST service, need include ngResouse module

Var eventApp = angular.module(‘eventsApp’, [‘ngResource’])

//simple resource immediately return

return $resource(‘/data/event/:id’,{id:’@id’}).get({id:1});

 

 eventsApp.factory('eventData', function ($resource, $q) {

    var resource = $resource('/data/event/:id', {id: '@id'});

    return {

        getEvent: function () {

            var deferred = $q.defer();

            resource.get({id: 1},

                function (event) {

                    deferred.resolve(event);

                },

                function (response) {

                    deferred.reject(response);

                });

 

            return deferred.promise;

        },

        save: function(event) {

            var deferred = $q.defer();

            event.id = 999;

            resource.save(event,

                function(response) { deferred.resolve(response);},

                function(response) { deferred.reject(response);}

            );

            return deferred.promise;

        }

    };

});

 

 

    1. $anchorScroll service, can work with html routing

$scope.scrollToSession= function(){ $anchorScroll(); }

    1. $cacheFactory service

var eventsApp = angular.module('eventsApp', ['ngResource', 'ngCookies'])

    .factory('myCache', function($cacheFactory) {

        return $cacheFactory('myCache', {capacity:3});

});

 

//controller

eventsApp.controller('CacheSampleController',

    function CacheSampleController($scope, myCache) {

        $scope.addToCache = function(key, value) {

            myCache.put(key, value);

        };

 

        $scope.readFromCache = function(key) {

            return myCache.get(key);

        };

                                                                                                                             

        $scope.getCacheStats = function() {

            return myCache.info();

        };

    }

);

 

g.       $compile service, It was used whenerver a page is loaded, process directive.  

You also can use it in your code, it can add a directive dynamically.

  $scope.appendDivToElement = function(markup) {

            return $compile(markup)($scope).appendTo(angular.element("#appendHere"));

        }

//html

<div class="container">

    <div ng-controller="CompileSampleController" style="padding:20px;">

 

        <div id="appendHere"></div>

        <br/>

        name:<input type="text" ng-model="name"/><br/>

        markup: <input type="text" ng-model="markup"/><br/> //markup = ‘<h3>{{name}}</h3>’

        <button class="btn" ng-click="appendDivToElement(markup)">Append</button>

 

    </div>

</div>

 

    1. $parse service, is used to evaluate an expression and turn that expression to function.

var fn= $parse(‘1+2’);

console.log(fn());

 

var getter=$parse(‘event.name’);

var setter=getter.assign;

var context={event:{name:’xxxx’}};

console.log(getter(context));

setter(context, ‘bbbbb’);

 

i.       $locale Service, angular-local_es.js for different language.

$scope.myFormat=$locale.DATETIME_FORMATS.fullDate;

 

j.       $timeout service same like window.setTimeout, but is Angular registered. 

 

k.      $exceptionHandler service

eventsApp.factory('$exceptionHandler', function() {  //this service with $

    return function (exception) {

        console.log("exception handled: " + exception.message);

    };

});

l.       $filter service

 

m.    $cookieStore Service  (Note,it not have function for expire date)

eventsApp.controller('CookieStoreSampleController',

    function CookieStoreSampleController($scope, $cookieStore) {

        $scope.event = {id: 1, name:"My Event"};

        $scope.saveEventToCookie = function(event) {

            $cookieStore.put('event', event);

        };

        $scope.getEventFromCookie = function() {

            console.log($cookieStore.get('event'));

        };

        $scope.removeEventCookie = function() {

            $cookieStore.remove('event');

        };

    }

);

 

n.      Other services: $interpolate $log $rootScope $window $document $rootElement

$rootScope is one per App, Prototypal Inheritance(all child $scope able to access it) , Injectable

Use too much Dom Services is not best practice.

$interpalateProvider can change {{}}expression delimeters.