2014-02-21 29 views
0

我正在設置一個rootScope變量來維護程序的狀態。這有效,但我不認爲這是'正確的'。有沒有更好的方法從數組中選擇一個對象?在Angular控制器中使用過濾器/對象的更好方法?

這是我目前的代碼。

angular.module('myApp.controllers', []) 
.controller('packingCtrl', ['$scope', '$http', '$filter', '$rootScope', function($scope, $http, $filter, $rootScope) { 
    $http.get('data/trayData.json').success(function(data) { 
     $scope.trays = data; 
    }); 
    var currentOrder = $rootScope.currentlyPacking;; 
    $http.get('data/orderData.json').success(function(data) { 
     $scope.orders = data; 
     $scope.current = $filter('filter')($scope.orders, {orderId: currentOrder}); 
    }); 
}]) 

在此先感謝您的任何見解/最佳實踐。

回答

0

您可以創建一個服務來保存您的狀態。每個服務實例都是單例,所以當服務被注入到各個控制器中時,所有服務都將看到相同的狀態。

var currentlyPackingSvc = function($http) { 
    var currentlyPacking = { 

    } 

    return { 
     currentlyPacking: currentlyPacking, 
     getTrays: function() { /* make $http call and update currentlyPacking */ }, 
     getOrders: function() { /* make $http call and update currentlyPacking */ } 
    } 
} 

angular.service('currentlyPackingSvc', ['$http', currentlyPackingSvc]); 

angular.controller('packingCtrl', ['$scope', '$http', '$filter', '$rootScope', 'currentlyPackingSvc' 
        function($scope, $http, $filter, $rootScope, currentlyPackingSvc) { 
    ... 
    var currentOrder = currentlyPackingSvc.currentlyPacking; 
    ... 
}]); 

假設您將'currentlyPacking'屬性作爲對象保留下來,這些更改應自動推送到您的範圍。

通過這種方式,您可以將所有狀態隔離爲一項可在任何地方使用的服務。

相關問題