Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-class doesn't update when it should after function invoked with ng-click is executed

I've got a problem with ng-class in AngularJS - it doesn't update properly.

View:

<div class="cal-day" ng-repeat="day in schedule">
    ...
    <div class="entry" ng-click="entryDetails(entry)" ng-repeat="entry in day.blockGrid"
     ng-class="{'selected': isSelected(entry), 'bg-{{entry.color}}': entry, 'bg-empty': !entry}">
         {{isSelected(entry)}}
         ...
    </div>
</div>

JS:

$scope.entryDetails = function(entry) {
    $scope.entryForDetails = entry;
};

$scope.isSelected = function(entry) {
    return $scope.entryForDetails === entry;
};

CSS class selected is implemented fine - when I replace isSelected(entry) with true in ng-class, the class gets applied properly.
Same thing with isSelected() function - it correctly prints true or false depending on whether the item is selected.
Even though both elements work, they somehow refuse to work together, and the div class doesn't get updated to selected when isSelected(entry) returns true.

Edit:

Model stored in day

  {
    "date": "6.6.2013",
    "blockGrid": [
      null,
      null,
      null,
      null,
      null,
      null,
      {
        "group": "ABCD",
        "subjectName": "AB CD",
        "subjectShorthand": "PW",
        "type": "c",
        "number": 4,
        "profName": "ABAB",
        "date": "2013-06-05T22:00:00.000Z",
        "venue": "329 S",
        "timetableBlock": 7,
        "color": 16,
        "_id": "51c3a442eb2e46a7220000e2"
      }
    ]
  }

As you can see, it's an array of 7 elements which are either null or contain an entry object.

I forgot to mention that posted section of my view is inside another ng-repeat. View code snippet above is now expanded to reflect that.

like image 274
fau Avatar asked Jun 23 '13 14:06

fau


1 Answers

Ng-class, as you have set it up, is wanting to evaluate a boolean expression, which your first expression in the object has done. However, the next two expressions are trying to evaluate the entry object, and not the result of isSelected(entry), which returns true/false.

So to correct:

ng-class="{'selected': isSelected(entry), 'bg':isSelected(entry), 'bg-empty':!isSelected(entry)}"

That is, unless you are trying something else. Also notice that I removed bg-{{entry.color}}. I have no clue how to evaluate a scope property within an ng-class, or if it is even possible.

Here is the working plunker demo. This may not be what you are after, but it can at least help you troubleshoot.

like image 137
rGil Avatar answered Nov 16 '22 10:11

rGil