AngularJS - 检查子数组是否包含某些内容

AngularJS - Check if subarray contains something

本文关键字:包含某 是否 数组 检查 AngularJS      更新时间:2023-09-26

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

{
"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 room,在那里又列出了另一个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 类表达式中使用该标志即可。


计算结果可以是表示空格分隔类名的字符串、数组或类名到布尔值的映射。对于映射,值为 true 的属性的名称将作为 css 类添加到元素中。

另请参阅 Array.some 及其用于旧版浏览器的填充程序。