angularjs 中使用 service 在controller 之间 share 对象和数据

在做angularjs 的UI 时,我们经常会遇到一个页面之间有几个controller,在controller 之间share 公共的一些数据和方法就变得比较困难,目前推荐的做法是创建一个service, 在service 中存储公共的数据,然后把service 注入到controller中来达到share 数据的目的。

下面是最简单的一个sample 列子

angularjs 模板页面, 有userContoller 和 customerController,我们将在这两个controller 之间共享数据, 具体定义如下:

<div ng-app="APP">
    <h2>angularjs sample</h2>
    <div ng-controller="userController">        
        <div>{{golbal_sitename}}</div>
        <div>{{controllerName}}</div>
        <div><button ng-click="sayHello()">sayHello</button></div>
    </div>
    <hr />
     <div ng-controller="customerController">        
        <div>{{golbal_sitename}}</div>
         <div>{{controllerName}}</div>
         <div><button ng-click="sayHello()">sayHello</button></div>
    </div>
</div>

angularjs js 页面, 在这个代码中我们定义了 module APP, userController 和customerController, 另外我们还定义了一个service, dataService,这个service 包含需要共享的数据和方法,在这里我们返回了一个属性golbal_sitename, 和 一个sayHello 方法。

然后,在声明controller 的时候,我们把dataservice 这个对象分别注入到userController 和customerController,注入完成后,我们就可以在controller 的代码中访问dataService共享的数据了。

var APP = angular.module('APP',[]).
controller('userController', ['$scope','dataService',function($scope,dataService) {
       $scope.controllerName='userController';
       $scope.golbal_sitename=dataService.golbal_sitename;
       $scope.sayHello =function(){
           dataService.sayHello($scope.controllerName);
       }
}]).
controller('customerController',['$scope','dataService', function($scope,dataService) {
       $scope.controllerName='customerController';
       $scope.golbal_sitename=dataService.golbal_sitename;
       $scope.sayHello =function(){
           dataService.sayHello($scope.controllerName);
       }
}]).
factory('dataService',function(){
    return {
        golbal_sitename:"this is the shared value",
        sayHello:function(msg){
            alert(msg);
        }
    }
});

最后的结果截图如下:

从图中我们可以看到

”this is the shared value“ 值来自dataService
sayHello 的具体实现也是在dataService中定义的。
 
这样我们就实现了在controller 之间共享对象。
 
原文地址:https://www.cnblogs.com/slardar1978/p/4203822.html