Fjarlaegur
Fjarlaegur

Reputation: 1443

Watching an object in AngularJS

I am using AngularJs 2 and i am having difficulties watching an object.

I have an object like the following in a directive:

scope.timelineFilter = {hasCapacity: true, onlyActivated: true, companyIdList: []};

I have 2 JQuery functions who change certain values of the object (Soon implementing the third)

$("[name='hasCapacity']").bootstrapSwitch().on('switchChange.bootstrapSwitch', function(event, state) {
    scope.timelineFilter.hasCapacity = state;
});

$("[name='activeOnly']").bootstrapSwitch().on('switchChange.bootstrapSwitch', function(event, state) {
    scope.timelineFilter.onlyActivated = state;
});

These functions work correctly. If i log the scope.timelineFilter after changing it, i can see the change from true to false (or the other way around)

Now i want to do a call to the backend each time this object changes. So i tried implementing a watcher like this:

scope.$watchCollection('timelineFilter', function() {
    console.log("Changed");
}, true);

I did set the third parameter to true for reference checking. The problem is, this event only fires when the page is loaded but when changing the properties, it does never fire anymore.

Also tried without the third parameter, using scope.$watch with and without the third parameter. Same result.

I searched SO, most people tried to watch arrays with objects, so that isn't viable for me as the backend expects an object.

How can i solve this problem? Is the problem in JQuery? By changing it in the JQuery method it does not register for the watcher?

Thanks!

Upvotes: 1

Views: 44

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190945

You are doing things outside of angular's digest cycle. You have to invoke it yourself:

$("[name='hasCapacity']").bootstrapSwitch().on('switchChange.bootstrapSwitch', function(event, state) {
    scope.timelineFilter.hasCapacity = state;
    scope.$digest();
});

$("[name='activeOnly']").bootstrapSwitch().on('switchChange.bootstrapSwitch', function(event, state) {
    scope.timelineFilter.onlyActivated = state;
    scope.$digest();
});

Upvotes: 1

Related Questions