我使用AngularJS + SocketIO和Controller As 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', 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();
,但已经正在进行" $申请"错误。
这是另一个带有Plunker答案的叉子的例子here:
Original with $scope
Mine with Controller As
如何更新$ filter找到的对象?
答案 0 :(得分:1)
您应该在原始集合中替换它,而不是在过滤后。
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;