AngularJS - Passing data between pages

You need to create a service to be able to share data between controllers.

app.factory('myService', function() {
 var savedData = {}
 function set(data) {
   savedData = data;
 }
 function get() {
  return savedData;
 }

 return {
  set: set,
  get: get
 }

});
In your controller A:

myService.set(yourSharedData);
In your controller B:

$scope.desiredLocation = myService.get();
Remember to inject myService in the controllers by passing it as a parameter.
If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.
app.controller('AController', function ($scope, $rootScope) {
$rootScope.varX = "XXX";
});

app.controller('BController', function ($scope, $rootScope) {
console.log("$rootScope.varX:", $rootScope.varX);
});
著做權歸做者全部。
商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
做者:Ye Huang
連接:http://www.zhihu.com/question/33565135/answer/69651500
來源:知乎

1. 基於ui-router的頁面跳轉傳參(1) 在AngularJS的app.js中用ui-router定義路由,好比如今有兩個頁面,一個頁面(producers.html)放置了多個producers,點擊其中一個目標,頁面跳轉到對應的producer頁,同時將producerId這個參數傳過去。.state('producers', {
    url: '/producers',
    templateUrl: 'views/producers.html',
    controller: 'ProducersCtrl'
})
.state('producer', {
    url: '/producer/:producerId',
    templateUrl: 'views/producer.html',
    controller: 'ProducerCtrl'
})
(2) 在producers.html中,定義點擊事件,好比ng-click="toProducer(producerId)",在ProducersCtrl中,定義頁面跳轉函數 (使用ui-router的$state.go接口):.controller('ProducersCtrl', function ($scope, $state) {
    $scope.toProducer = function (producerId) {
        $state.go('producer', {producerId: producerId});
    };
});
(3) 在ProducerCtrl中,經過ui-router的$stateParams獲取參數producerId,譬如:.controller('ProducerCtrl', function ($scope, $state, $stateParams) {
   var producerId = $stateParams.producerId;
});
2. 基於factory的頁面跳轉傳參舉例:你有N個頁面,每一個頁面都須要用戶填選信息,最終引導用戶至尾頁提交,同時後一個頁面要顯示前面全部頁面填寫的信息。這個時候用factory傳參是比較合理的選擇(下面的代碼是一個簡化版,根據需求能夠不一樣定製):.factory('myFactory', function () {
    //定義factory返回對象
    var myServices = {};    
    //定義參數對象
    var myObject = {};
    
    /**
     * 定義傳遞數據的set函數
     * @param {type} xxx
     * @returns {*}
     * @private
     */
    var _set = function (data) {
       myObject = data;     
    };

    /**
     * 定義獲取數據的get函數
     * @param {type} xxx
     * @returns {*}
     * @private
     */
    var _get = function () {
        return myObject;
    };

    // Public APIs
    myServices.set = _set;
    myServices.get = _get;
    
    // 在controller中經過調set()和get()方法可實現提交或獲取參數的功能
    return myServices;
  
});
3. 基於factory和$rootScope.$broadcast()的傳參(1) 舉例:在一個單頁中定義了nested views,你但願讓全部子做用域都監聽到某個參數的變化,而且做出相應動做。好比一個地圖應用,某個$state中定義元素input,輸入地址後,地圖要定位,同時另外一個狀態下的列表要顯示出該位置周邊商鋪的信息,此時多個$scope都在監聽地址變化。PS: $rootScope.$broadcast()能夠很是方便的設置全局事件,並讓全部子做用域都監聽到。.factory('addressFactory', ['$rootScope', function ($rootScope) {
    // 定義所要返回的地址對象   
    var address = {};
    
    // 定義components數組,數組包括街道,城市,國家等
    address.components = [];

    // 定義更新地址函數,經過$rootScope.$broadcast()設置全局事件'AddressUpdated'
    // 全部子做用域都能監聽到該事件
    address.updateAddress = function (value) {
    this.components = value.slice();
    $rootScope.$broadcast('AddressUpdated');
    };
    
    // 返回地址對象
    return address;
}]);
(2) 在獲取地址的controller中:// 動態獲取地址,接口方法省略
var component = {
    addressLongName: xxxx,
    addressShortName: xxxx,
    cityLongName: xxxx,
    cityShortName: xxxx         
};

// 定義地址數組
$scope.components = [];

$scope.$watch('components', function () {
    // 將component對象推入$scope.components數組
    components.push(component);
    // 更新addressFactory中的components
    addressFactory.updateAddress(components);
});
(3) 在監聽地址變化的controller中:// 經過addressFactory中定義的全局事件'AddressUpdated'監聽地址變化
$scope.$on('AddressUpdated', function () {
   // 監聽地址變化並獲取相應數據
   var street = address.components[0].addressLongName;
   var city = address.components[0].cityLongName;

   // 經過獲取的地址數據能夠作相關操做,譬如獲取該地址周邊的商鋪,下面代碼爲本人虛構
   shopFactory.getShops(street, city).then(function (data) {
       if(data.status === 200){
          $scope.shops = data.shops;  
       }else{
          $log.error('對不起,獲取該位置周邊商鋪數據出錯: ', data);
       }
   });
});
4. 基於localStorage或sessionStorage的頁面跳轉傳參注意事項:經過LS或SS傳參,必定要監聽變量,不然參數改變時,獲取變量的一端不會更新。AngularJS有一些現成的WebStorage dependency可使用,譬如gsklee/ngStorage · GitHub,grevory/angular-local-storage · GitHub。下面使用ngStorage來簡述傳參過程:(1) 上傳參數到localStorage - Controller A// 定義並初始化localStorage中的counter屬性
$scope.$storage = $localStorage.$default({
    counter: 0
});

// 假設某個factory(此例暫且命名爲counterFactory)中的updateCounter()方法
// 能夠用於更新參數counter
counterFactory.updateCounter().then(function (data) {
    // 將新的counter值上傳到localStorage中
    $scope.$storage.counter = data.counter;
});
(2) 監聽localStorage中的參數變化 - Controller B$scope.counter = $localStorage.counter;
$scope.$watch('counter', function(newVal, oldVal) {
    // 監聽變化,並獲取參數的最新值
    $log.log('newVal: ', newVal);    
});

http://www.zhihu.com/question/33565135html

service 到底這麼用?數組

...session

相關文章
相關標籤/搜索