Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何更新数组中的对象_Arrays_Angularjs - Fatal编程技术网

Arrays 如何更新数组中的对象

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

我正在使用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', 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;