服务:在AngularJS 中,服务是一个函数或对象
在写控制器的时候,不要复用controller,当我们的controller里面有相同的代码时,此时需要把它抽取成一个服务,所有的服务都符合依赖注入的原则,服务在整个应用的生命周期中存在,可用来共享数据。
Angular提供了3种方法来创建服务,factory,service,provider
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="name"/> {{name}}
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
var app=angular.module("myApp",[]);
//自定义服务provider,myService1为服务名
app.provider('myService1', function () {
this.$get = function () {
return{
message: 'customprovider Message'
}
}
});
//自定义服务service
app.service('myService2', function () {
return ['上海'];
});
//自定义工厂factory
app.factory("myService3", [function () {
return [1, 2, 3, 4, 5, 6];
}]);
//service和factory类似,但返回的东西必须是对象
app.controller('myCtrl',function($scope,myService1,myService2,myService3){
$scope.name = '橘子';
console.log(myService1);
console.log(myService2);
console.log(myService3);
});
</script>
</body>
</html>
效果截图

共享数据
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="firstCtrl">
<input type="text" ng-model="data.name"/>
<input type="text" ng-model="Data.message"/>
<p>first{{data.name}}</p>
<p>first{{Data.message}}</p>
</div>
<div ng-controller="secondCtrl">
<p>second{{data.name}}</p>
<p>second{{Data.message}}</p>
</div>
</div>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
var app = angular.module("myApp",[]);
app.factory('Data',function(){
return{
message:'共享的数据'
}
});
app.controller('firstCtrl',function($scope,Data){
$scope.data ={
name: '橘子'
};
$scope.Data = Data;
});
app.controller('secondCtrl',function($scope,Data){
$scope.Data = Data;
});
</script>
</body>
</html>