我在AngularJS中遇到ng-class问题-无法正确更新。

查看:

<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类实现良好-当我在ng-class中将isSelected(entry)替换为true时,该类将得到正确应用。
与isSelected()函数相同-根据选择的项目正确地输出true或false。
即使两个元素都起作用,但它们还是以某种方式拒绝一起工作,并且当isSelected(entry)返回true时,div类不会更新为selected。

编辑:

模型存储在日期
  {
    "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"
      }
    ]
  }

如您所见,它是由7个元素组成的数组,这些元素为null或包含一个入口对象。

我忘了提及我发表的观点是在另一个ng-repeat中。上面的查看代码段现已扩展以反射(reflect)这一点。

最佳答案

正如您已经设置的那样,Ng类想要评估一个 bool 表达式,您在对象中的第一个表达式已经完成了该操作。但是,接下来的两个表达式试图评估entry对象,而不是isSelected(entry)的结果,后者返回true/false。

因此要更正:

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

也就是说,除非您尝试其他操作。还要注意,我删除了bg-{{entry.color}}。我不知道如何评估ng-class内的作用域属性,甚至是不可能的。

Here is the working plunker demo。这可能不是您要追求的目标,但至少可以帮助您进行故障排除。

关于angularjs - 执行ng-click调用的函数后,ng-class不会更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17261896/

10-13 07:52