Question

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>
Was it helpful?

Solution

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
});

OTHER TIPS

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.

Try $route.reload(). It works very well for directives that are only evaluated once when the page is loaded (like the type that uses JQuery to do DOM manipulation).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top