Reputation: 35
I'm building a dashboard using AngularJS + SocketIO and Controller As vm syntax.
I want to update my view when a specific IO message got receive:
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
});
I tried adding a $scope.$apply();
after the update but had the "$apply already in progress" error.
Here is another example with a fork of a Plunker answer found here:
Original with $scope
Mine with Controller As
What can I do to update the object found by $filter ?
Upvotes: 1
Views: 1556
Reputation: 14992
You should to replace it in the original collection, not in the filtered.
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
Other method:
var index = vm.products.map(function(v){return v._id}).indexOf(updated_product._id);
vm.products[~index?index:vm.products.length] = updated_product;
Upvotes: 1