Amal Antony
Amal Antony

Reputation: 6827

What's the explanation behind this (seemingly) unexpected behavior from ng-class.

Here's a plunker I created: http://plnkr.co/edit/ZoKsO7wu5OvCYtwEi9Iy?p=preview.

It's seen that a cannot be selected now. However, the other items(b, c) in the list can be selected. Once another item has been selected and it's selection cleared, a can be selected again!

Why is ng-class behaving unexpectedly here?

Upvotes: 0

Views: 59

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32377

I wouldn't use jQuery for that but if you still want then you must let angular know of any modifications you do.

You may think that you cleared the selection, but what the jQuery callback only does is to remove the class. from angular's perspective it is still selected , so it doesn't fire ngClass watchExpression to add the class again.

Use $scope.$apply():

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

Here is a plunker: http://plnkr.co/edit/C6jcmfU8V4tab8oeDJES?p=preview

I moved your click event listener into the controller:

$('#removeSelection').click(function(){
  $scope.$apply(function(){
    $scope.selectedId = null;
  })
});

Much better to just use angular built-in ngClick:

<a ng-click="selectedId = null">Click to Clear Selection</a>

Upvotes: 3

Related Questions