转载于
作者:海底苍鹰
地址:http://blog.51yip.com/jsjquery/1602.html
1.在app.js 中声明了模块的依赖
1 var phonecatApp = angular.module('phonecatApp', [ 2 'ngRoute', 3 'phonecatControllers', 4 'directivesmy', 5 'servicesmy', //服务依赖关系 6 'pascalprecht.translate' 7 ]);
2. 在service.js 中写自定义服务 工厂 提供...
1 'use strict'; 2 3 4 var appservices=angular.module('servicesmy', []); 5 6 // factory 7 appservices.factory('factorytest',['$window',function($window){ 8 var test={ 9 firstname:"xie", 10 lastname:function(){ 11 return "xie"; 12 } 13 }; 14 $window.alert('factorytest'); //内置服务可以注入 15 return test; 16 }]); 17 /* Services */ 18 appservices.service('servicetest',['$window',function($window){ 19 $window.alert("servicetest"); 20 this.firstname="thank"; 21 this.lastname=function(){ 22 return "zhang"; 23 } 24 } 25 ]); 26 // provider 27 appservices.provider('providertest',[ 28 function(){ 29 this.test={ 30 "firstname":"xie", 31 "lastname":"ni", 32 } 33 this.$get=function(){ 34 return this.test; 35 } 36 } 37 ]);
3. 在控制器中 controllers.js 调用自定义服务
1 //引进自定义的服务 2 phonecatControllers.controller('SomeController',function($scope,factorytest,servicetest,providertest) { 3 $scope.title = '点击展开'; 4 $scope.text = '这里是内部的内容。'; 5 $scope.facetorytests = factorytest.firstname+" "+factorytest.lastname(); 6 $scope.servicetests = servicetest.firstname+" "+servicetest.lastname(); 7 $scope.providertests = providertest.firstname+" "+providertest.lastname; 8 });
4. 在HTML中 显示效果
1 <p>{{facetorytests}}</p> 2 <p>{{servicetests}}</p> 3 <p>{{providertests}}</p>
5.Server 和factory 可以实现controller 之间的数据共享;而不是通过调用共同的从conctroller 来共享数据;
。。。。。。。。。