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 之間共享對象。
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM