AngularJS $watch variable and reevaluate ng-class expression

10,679

Solution 1

If the bookmark ID's are being changed in code handled by angular (such as in a controller, a directive, a service, an $http callback, etc.) then you don't need to do anything at all. Angular will automatically re-evaluate isBookmarked(event.id) when it needs to in order to ensure that the UI is always up to date.

If, for some reason, the updates must be done outside of code that is handled by angular (such as in an external library), then you can manually force angular to update. However, it is highly recommended to just ensure that the code is handled by angular. You can usually do this, but it depends on the situation.

If you need to force it, then use $scope.$apply as follows:

$scope.$apply(function() {
  // Write code here to update bookmark ID's
});

Solution 2

Assuming the class you want to add a class named "bookmarked" to the anchor tag and that isBookmarked returns a boolean, use this (fiddle):

<a ng-repeat="event in events" 
   ng-class="{bookmarked: isBookmarked(event.id)}" 
   class="icon__bookmark">{{event.name}}</a>

You should not have to call $apply if the bookmarks array is within the controller, please see the fiddle I provided.

Share:
10,679
Martin Broder
Author by

Martin Broder

Martin Broder Front-end Developer &amp; Web-Designer martinbroder.com

Updated on June 13, 2022

Comments

  • Martin Broder
    Martin Broder almost 2 years

    I'm trying to implement a bookmark-like function into my app and have to watch a variable, which stores all the bookmarked ID's. Based on that variable I have to tell ng-class to reevaluate it's function expression so the class bookmarked get's added or not.

    How do I tell ng-class to run again when the variable $scope.Bookmarks changes?

    <a ng-repeat="event in events"
       ng-class="isBookmarked(event.id)"
       class="icon__bookmark"></a>