gerrod
gerrod

Reputation: 6627

$scope.$watch on an array is not updating when the values are added from a directive

I'm sure this is just a newbie mistake... here's the plunker: http://plnkr.co/edit/L5702XAtQwBRmzP2kqoA?p=preview

I have a directive which updates a value based on a selected checkbox:

// --- 8< ---
// Detect click on checkbox, get value, etc... then:
// --- 8< ---
scope.$apply(function() {
    if ($this.prop("checked")) {
        selected.push(value);
    } else {
        for (var i = 0; i < selected.length; i++) {
            if (selected[i] == value) {
                selected.splice(i, 1);
                break;
            }
        }
    }

    console.log("selected updated to: " + selected)
});

I'm watching that collection back in the page's controller:

$scope.$watch("model.selected", function(selected) {
    console.log("----- Controller updated with: ", selected);
});

The console.log statement here only shows once, when the page first loads. However, on the page, I've got a binding which shows the selected values array:

Selected: {{ model.selected }}

This does get updated.

Why doesn't my watch get updated, too?

Upvotes: 0

Views: 46

Answers (2)

Kamrul
Kamrul

Reputation: 7301

if you only need to monitor the length changes then use

$scope.$watch("model.selected.length", function() {
    console.log("----- Controller updated with: ", $scope.model.selected);
});

NB: watching only length will be much faster operation.

Upvotes: 2

Ben Priebe
Ben Priebe

Reputation: 365

To be notified when a collection (ie. array) has values added, removed, changed you need to use the $scope.$watchCollection method.

Change this:

$scope.$watch("model.selected", function(selected) {
    console.log("----- Controller updated with: ", selected);
});

to this:

$scope.$watchCollection("model.selected", function(selected) {
    console.log("----- Controller updated with: ", selected);
});

Here is the updated plunkr:

http://plnkr.co/edit/f2xCge2ragh5uWKRRwof?p=preview

Upvotes: 2

Related Questions