Arrays 如何更新数组中的对象
我正在使用AngularJS+SocketIO和Controller作为vm语法构建一个仪表板 我想在收到特定IO消息时更新我的视图:Arrays 如何更新数组中的对象,arrays,angularjs,Arrays,Angularjs,我正在使用AngularJS+SocketIO和Controller作为vm语法构建一个仪表板 我想在收到特定IO消息时更新我的视图: var vm = this; vm.products = ProductService.query(); //Get an array of Products //When receiving an update through SocketIO, update the view SocketService.on('product:update', funct
var vm = this;
vm.products = ProductService.query(); //Get an array of Products
//When receiving an update through SocketIO, update the view
SocketService.on('product:update', function(updated_product) {
var found = $filter('filter')(vm.products, {_id: updated_product._id}, true);
if(found.length) { //Product was found, updating product
$filter('filter')(vm.products, {_id: updated_product._id}, true)[0] = updated_product;
} else vm.products.push(updated_product); //else add a new product
});
我尝试添加一个$scope.$apply()代码>在更新后,但出现“$apply ready in progress”错误
下面是另一个例子,找到了一个类似于Plunker的答案:
如何更新$filter找到的对象 您应该在原始集合中替换它,而不是在过滤后的集合中
var found = $filter('filter')(vm.products, {_id: updated_product._id}, true);
if(found.length) { //Product was found, updating product
// found[0] = updated_product;
vm.products[vm.products.indexOf(found[0])] = updated_product;
} else vm.products.push(updated_product); //else add a new product
其他方法:
var index = vm.products.map(function(v){return v._id}).indexOf(updated_product._id);
vm.products[~index?index:vm.products.length] = updated_product;