1

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 ?

0

1 Answer 1

1

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; 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.