2014-09-22 60 views
0

我有一個名爲「categories」的主對象,它由DataService返回,並被許多不同的控制器調用。如何引用Angular Service返回的數組,以維持狀態?

.service('DataService', ['$http', '$q', '$timeout', function($http, $q, $timeout) { 

    var categories = {}; 

    // Return public API. 
    return({ 
     setCategory: setCategory, 
     getCategory: getCategory 
    }); 

    function setCategory(activities, details) { 
     var name = details.shortName, 
      category = {}; 
     category.activities = activities; 
     category.details = details; 
     categories[name] = category; 
    } 

    function getCategory(name) { 
     return categories[name]; 
    } 

從控制器訪問categories以維持所有控制器之間的狀態的正確方法是什麼?

例如,在控制器1我要搶匹配namecategories對象的屬性,然後添加新值包含在它的活動:

$scope.category = getCategory(name); 
$scope.category.activities[2].input = true; 

話,我希望能夠訪問值category.activities[2].input使用getCategories服務的地方。但據我所知,這是行不通的,因爲我已將categories[name]重新分配到$scope.category,對吧?

或者我錯了,還是完全採用錯誤的方法?調用categories對象中對象的最佳方式是什麼,這樣可以讓我保持所有控制器的狀態?

+0

只是一定要使用DataService.setCategory控制器進行更改每次。然後,您可以使用$ broadcast來發送服務已更改的消息,並使用$ on觸發'getCategory'方法的刷新,以便在每個控制器中擁有最新的模型。 – 2014-09-22 19:00:33

回答

0

請不要使用$broadcast。使用$watch

.value('categories',{}) 
.service("myService",function(categories,$rootScope) { 
    $rootScope.$watch(function(){ 
     return categories; 
    },function(val){ 
     console.log("Some controller, any controller, has updated categories!"); 
    },true); 
}) 
0

作爲一個建議,你可以調用DataService.setCategory每個控制器進行更改的時間。然後,您可以使用$ broadcast發送服務已更改的消息,並使用$ on訂閱並觸發'getCategory'方法的刷新,以便在每個控制器中擁有最新模型。

例如,在您的服務:

.service('DataService', ['$rootScope', '$http', '$q', '$timeout', function($rootScope, $http, $q, $timeout) { 

    function setCategory(activities, details) { 
     var name = details.shortName, 
     category = {}; 
     category.activities = activities; 
     category.details = details; 
     categories[name] = category; 

     $rootScope.$broadcast('categories:updated'); 
    } 

並在控制器:

.controller('ControllerOne', ['$scope', '$rootScope', 'DataService', function($scope, $rootScope, DataService) { 

    $scope.category = DataService.getService(name); 

    $scope.category.activities[2].input = true; 

    DataService.setCategory(category.activities, category.details); 

}]) 

.controller('ControllerTwo', ['$scope', '$rootScope', 'DataService', function($scope, $rootScope, DataService) { 

    $scope.category = DataService.getCategory(name); 

    $scope.$on('categories:updated', function(){ 
     $scope.category = DataService.getCategory(name)    
    }); 

}]);