如何引用Angular Service返回的数组,以便维护状态
How to reference array returned by Angular Service, in order to maintain state?
我有一个名为"categories"的主对象,它由DataService
返回,并由许多不同的控制器调用。
.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
的值。但据我所知,这行不通,因为我已经将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)
});
}]);
相关文章:
- 从组件状态的数组中删除元素
- 如何在React中更改处于状态的数组
- ReactJS-这个状态中的数组在删除时被正确更新,但结果是't,直到以后的状态发生变化
- 从数组中删除元素,然后保留其状态以备将来使用,而不使用全局变量
- 如何使用Handlebars.js按状态拆分对象数组
- 如何从状态数组中删除项目
- React-Redux:当连接到处于状态的数组时无限循环
- 在 ReactJs 状态上将项目添加到数组中,并超时以进行自我删除
- 从 0 和 1 的数组恢复复选框的状态
- 如何推送到实际对象的数组最后状态,清除它并像新对象一样单独编辑
- 反应 redux 与给定数组的合并状态
- 将状态的数组长度设置为 0,但绑定列表仍剩下一个元素
- 在闭包中公开数组的状态,而不允许从外部对其进行编辑
- ReactJs-如何更新数组中的状态
- $_POST 变量保持活动状态多长时间,PHP 如何决定 post 数组中的内容
- Reactjs-对处于状态的对象数组进行排序
- 如何引用Angular Service返回的数组,以便维护状态
- 使用单例模式维护整个应用中的数组状态
- 清除Redux中的数组状态
- 如何在Node模块之间共享数组状态