[英]How to reference array returned by Angular Service, in order to maintain state?
我有一个称为“类别”的主对象,该对象由DataService
返回,并由许多不同的Controller调用。
.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
的正确方法是什么?
例如,在Controller1中,我想获取与name
匹配的categories
对象属性,然后向其中包含的活动添加新值:
$scope.category = getCategory(name);
$scope.category.activities[2].input = true;
然后,我希望能够在使用getCategories
服务的任何地方访问category.activities[2].input
的值。 但是据我所知,这是行不通的,因为我已经将$scope.category
categories[name]
重新分配给$scope.category
,对吗?
还是我做错了,还是采取了完全错误的方法? 从categories
对象调用对象的最佳方法是什么,该方法将允许我保留所有控制器之间的状态?
请不要使用$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);
})
建议您每次控制器进行更改时都可以调用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)
});
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.