AngularJs允许开发者创建自定义服务,用于实现特定的功能。主要使用的服务类型包括:value、constant、factory、service。
1.value与constant
二者在使用上没有太大区别,基本意义都是为模块提供一个值,可以是字符串也可是JS对象。
2.factory
可以提供一个服务工厂,通常返回一个函数,具体语法为:
angular.module('myApp',[]).factory('factoryName',function(args){ return function(otherArgs){ //some operates args & otherArgs } })
3.service
service通常用作在控制器中实现特定功能,该方法接受的第二个参数是一个构造函数,并且使用这个构造函数来创建service的一个对象。service也可以接收依赖注入:
function serviceConstructor(arg1,arg2){ //some operates. } angular.module('myApp',[]).service('serviceName',['arg1','arg2',serviceConstructor]);
以下示例说明了这几种自定义服务的使用:
<!DOCTYPE HTML> <html ng-app='myApp'> <head> <meta charset='ut-8'> <title>Some title</title> <style type="text/css"> p{color: red;margin-left: 15px;} input{width: 150px;} </style> </head> <body ng-controller='someCtrl'> <h2>Custom service</h2> Censored words:<br> <p>{{words | json}}</p> <hr> Enter phrase:<br> <input type='text' ng-model='inPhrase'><hr> Filtered by factory: <p>{{censorFactory}}</p> Filtered by service: <p>{{censorService}}</p> <script src='http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js'></script> <script> var app = angular.module('myApp',[]); app.value('words',["can't","quit","bug"]) .constant('repString',"####"); app.factory('censorF',function(words,repString){ return function(inString){ var out = inString; for (i in words) { out = out.replace(words[i],repString); }; return out; } }) function censorObj(words,repString){ this.censor = function(inString){ var outString = inString; for(i in words){ outString = outString.replace(new RegExp(words[i],'g'),repString); } return outString; } this.censoredWords = function (){ return words; } } app.service('censorS',['words','repString',censorObj]) .controller('someCtrl',function($scope,censorF,censorS){ $scope.words = censorS.censoredWords(); $scope.inPhrase = ''; $scope.censorFactory = censorF(''); $scope.censorService = censorS.censor(''); $scope.$watch('inPhrase',function(newValue,oldValue){ $scope.censorFactory = censorF(newValue); $scope.censorService = censorS.censor(newValue); }); }); </script> </body> </html>
以上是一个关键词过滤的示例,使用factory和service实现了同样的过滤功能。值得注意的是:
JavaScript并不提供类似于JAVA的replaceAll方法,replace函数只能匹配第一个词并进行替换,若需要使用全部匹配替换,则需要使用RegExp,或使用如下的方法:
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { if (!RegExp.prototype.isPrototypeOf(reallyDo)) { return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith); } else { return this.replace(reallyDo, replaceWith); } }