一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

angularjs中factory,service,provider 自定义服务的不同

时间:2022-11-14 22:02:39 编辑:袖梨 来源:一聚教程网

一,factory,service,provider自定义服务,services.js

代码如下 复制代码

'use strict';

/* Services */

var phonecatServices = angular.module('phonecatServices', []);

phonecatServices.factory('facetorytest', ['$window', //factory方式
function($window){
var test = {
firstname:"tank",
lastname:function(){
return "zhang";
}
};
$window.alert('aaaa'); //内置服务可以注入
return test;
}
]);

phonecatServices.service('servicetest', ['$window', //service方式
function($window){
$window.alert('bbbb'); //内置服务可以注入
this.firstname = "tank";
this.lastname = function(){
return "zhang";
}
}
]);

phonecatServices.provider('providertest',[ //provider方式,内置服务不可以注入
function(){
this.test = {
"firstname":"tank",
"lastname":"zhang"
}
this.$get = function () {
return this.test;
};
}
]);

二,controller调用自定义模块,controllers.js

代码如下 复制代码

'use strict';

/* Controllers */

var phonecatControllers = angular.module('phonecatControllers', []);

//写过js function的对这种调用方式,很熟悉,服务名称不能变
function TestCtrl($scope,facetorytest,servicetest,providertest) {
$scope.facetorytest = facetorytest.firstname+" "+facetorytest.lastname();
$scope.servicetest = servicetest.firstname+" "+servicetest.lastname();
$scope.providertest = providertest.firstname+" "+providertest.lastname;
}

//这种调用方式根jquery非常的像,服务名称也不能变
phonecatControllers.controller('TestCtrl',function($scope,facetorytest,servicetest,providertest) {
$scope.facetorytest = facetorytest.firstname+" "+facetorytest.lastname();
$scope.servicetest = servicetest.firstname+" "+servicetest.lastname();
$scope.providertest = providertest.firstname+" "+providertest.lastname;
});

//以注入的方式来调用,服务名称可以改变
phonecatControllers.controller('TestCtrl',['$scope',"facetorytest","servicetest","providertest",
function($scope,facetory111,service111,provider111) { //自定义,服务名称
$scope.facetorytest = facetory111.firstname+" "+facetory111.lastname();
$scope.servicetest = service111.firstname+" "+service111.lastname();
$scope.providertest = provider111.firstname+" "+provider111.lastname;
}
]);www.111com.net

三,创建app把上面的service和controller接合到一起。app.js

代码如下 复制代码

'use strict';

/* App Module */

var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatControllers', //上面定义的controller
'phonecatServices' //上面自定义的服务
]);

四,html中显示

代码如下 复制代码





Google Phone Gallery









{{facetorytest}}


{{servicetest}}


{{providertest}}



显示结果:

tank zhang
tank zhang
tank zhang

五,错误纠正

在网上看到,有人说service是不能注入内置服务器的,但是实际操作结果是provider是不能注入内置服务的。我用的angularjs的版本是AngularJS v1.2.14

代码如下 复制代码

phonecatServices.provider('providertest',['$window',
function($window){
$window.alert('cccc'); //报错
this.test = {
"firstname":"tank",
"lastname":"zhang"
}
this.$get = function () {
return this.test;
};
}
]);

热门栏目