标签:
Angularjs 提供了3种方法来创建并注册我们自己的 service.
1.Factory
2.Service
3.Provider
一. Factory:
1. 下面构建了一个MyFactory, 用于设置个人信息,并展示个人信息。
Note: 1. 必须在里面调用return 否则会报错
2. 所有的可访问的方法都放到了Service里面
app.factory(‘MyFactory‘,function(){
var service = {};
var _name = ‘‘;
var _age = ‘‘;
service.SetInfo = function(name,age){
_name = name;
_age = age;
}
service.ShowInfo = function(){
return _name+‘:‘+_age;
}
return service;
});
2. 可以将通过function(MyFactory)中将服务注册到
Controller中. 控制台就会打印出Frank:23
var app = angular.module(‘myapp‘)
app.controller(‘InjectCtrl‘,function ($scope,MyFactory) {
MyFactory.SetInfo(‘Frank‘,23);
console.log(MyFactory.ShowInfo());
});
二. Service
1. Service与Factory用法差不多,区别在于不需要Return
一个对象.
var app = angular.module(‘myapp‘)
app.controller(‘InjectCtrl‘,function ($scope,MyService) {
MyService.SetInfo(‘Frank‘,23);
console.log(MyService.ShowInfo())
});
app.service(‘MyService‘, function(){
var _name = ‘‘;
var _age = ‘‘;
this.SetInfo = function(name,age){
_name = name;
_age = age;
}
this.ShowInfo = function(){
return _name+‘:‘+_age;
}
});
三. Provider:
1. Provider: 通过#Get方法实现数据的返回.
app.provider(‘MyProvider‘,function(){
var service = {};
var _name = ‘‘;
var _age = ‘‘;
service.SetInfo = function(name,age){
_name = name;
_age = age;
}
service.ShowInfo = function(){
return _name+‘:‘+_age;
}
this.$get = function(){
return service;
}
});
标签:
原文地址:http://www.cnblogs.com/yangtao92/p/4639028.html