Integrating Services in a Module

The code in Listing 25.10 shows an example of integrating value, constant, factory, and service services into a single module. The example is very basic and easy to follow. Notice that censorWords and repString are injected into and used in the factory and service definitions.

Lines 4–13 implement a factory service that returns a function that censors a string. Notice that line 26 calls the factory directly to censor the string.

Lines 14–23 implement a service service by first defining an object constructor and then, on line 23, registering the service to the application. Notice that line 27 calls the censor() method defined in the constructor to censor the text.

Listing 25.10 service_custom.js: Implementing and consuming custom services in an AngularJS controller


01 var app = angular.module('myApp', []);
02 app.value('censorWords', ['bad','mad','sad']);
03 app.constant('repString', "****");
04 app.factory('censorF', ['censorWords', 'repString',
05                         function (cWords, repString) {
06   return function(inString) {
07     var outString = inString;
08     for(i in cWords){
09       outString = outString.replace(cWords[i], repString);
10     }
11     return outString;
12   };
13 }]);
14 function CensorObj(cWords, repString) {
15   this.censor = function(inString){
16     var outString = inString;
17     for(i in cWords){
18       outString = outString.replace(cWords[i], repString);
19     }
20     return outString;
21   };
22 }
23 app.service('censorS', ['censorWords', 'repString', CensorObj]);
24 app.controller('myController', ['$scope', 'censorF', 'censorS',
25                                 function($scope, censorF, censorS) {
26     $scope.censoredByFactory = censorF("mad text");
27     $scope.censoredByService = censorS.censor("bad text");
28   }]);


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.120.178