AngularJS - 检查子数组是否包含某些东西

AngularJS - Check if subarray contains something

我有一个教室列表,每个教室都有一组要对教室执行的操作。

{
"id": 1,
"name": "GR302",    
"actions": [
  {
    "date": "19/04/2011",        
    "deadline": "21/04/2011",
    "priority": "high"
  },
  {
    "date": "15/01/2012",        
    "deadline": "20/12/2014",
    "priority": "low"
  }
],

}

我用 ng-repeat: room in rooms 和另一个 ng-repeat: action in room.actions. 现在我想在有高优先级操作的房间名称旁边放置一个标志。但我不知道如何,我是 AngularJS 的初学者。我唯一能想到的就是使用 ng-model & ng-class?

<h4>{{room.name}} <span class="glyphicon" ng-class="(something) ? 'glyphicon-flag' : ''"></span></h4>

你可以用很多不同的方式来做到这一点,ng-class 足够灵活,可以接受一系列表达式、对象、数组和字符串。

你可以这样做:-

 ng-class="{'glyphicon-flag' : action.priority == 'high'}"

 <!--More flexible version, Here you can add more key value pairs if you need to specify different classes for different priority-->
 ng-class="{'high' : 'glyphicon-flag'}[action.priority]" 

 ng-class="{true, 'glyphicon-flag'}[action.priority == 'high']"

甚至用表达式

  ng-class="action.priority == 'high' ?  'glyphicon-flag' : ''"

如果你想在上一级做这个,那么:

在你的控制器中创建作用域函数:

 $scope.isFlagged = function(actions){
    if(!angular.isArray(actions)) return false;

    return actions.some(function(action){
       return action.priority === 'high';
    });
 }

在你看来只是做:-

ng-class="{true, 'glyphicon-flag'}[isFlagged(room.actions)]"

或者,如果在您的情况下每个房间的操作数量不会动态变化,那么您应该在设置房间的视图模型时在控制器中添加一个 属性,这将提高性能.

示例:-

angular.forEach($scope.rooms , function(room) {
    room.isFlagged = isFlagged(room.actions); //Add a property on the room object
});

function isFlagged(actions){
    if(!angular.isArray(actions)) return false;

    return actions.some(function(action){
       return action.priority === 'high';
    });
 }

并在你的 ng-class 表达式中使用标志。


The result of the evaluation can be a string representing space delimited class names, an array, or a map of class names to boolean values. In the case of a map, the names of the properties whose values are truthy will be added as css classes to the element.

另请参阅 Array.some 及其针对旧版浏览器的 shim。