AngularJS中自定义服务的常见方式及特点
发布时间:2020-12-17 09:11:11 所属栏目:安全 来源:网络整理
导读:一、自定义服务的常见方式 1. $provide.provider 1.1 返回基本类型 var myApp = angular.module( 'app' ,[], function ($provide) { $provide.provider( 'customService' , function () { this .$get = function () { return 'customService message....' ;
一、自定义服务的常见方式1. $provide.provider1.1 返回基本类型var myApp = angular.module('app',[],function($provide){
$provide.provider('customService',function(){
this.$get = function() {
return 'customService message....';
};
});
});
//在模块内定义一个控制器firstController,并且注入了customService对象,customService参数放前放后都不要紧,都会自动匹配
myApp.controller('firstController',function($scope,customService){
console.log(customService); //测试注入的对象
});
1.2 返回对象类型var myApp = angular.module('app',function($provide){
// 自定义的第二个服务
$provide.provider('customService2',function(){
this.$get = function() {
return {
message : 'customService2 message....',
show:function(){
alert("hi");
}
}
};
});
});
//在模块内定义一个控制器firstController,并且注入了customService对象,customService参数放前放后都不要紧,都会自动匹配
myApp.controller('firstController',customService2){
console.log(customService2.message); //测试注入的对象
console.log(customService2.show()); //测试注入的对象
});
2
|