如何从 ng-class 检查数组中是否有内容

How to check if something is in array from ng-class

我想做这样的事情:

var list = [1,2,3,4,5]
if(2 in list){
  return true
}

来自 ng-class,所以我尝试了:

ng-class="this.id in list ? 'class-1' : 'class-2' ">

但是没有用,抛出错误

Syntax Error: Token 'in' is an unexpected token at ...

对于数组,您将使用 indexOf,而不是 in,后者用于对象

if ( list.indexOf(this.id) !== -1 ) { ... }

所以

ng-class="{'class-1' : list.indexOf(this.id) !== -1, 'class-2' : list.indexOf(this.id) === -1}"

看下面的代码:

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
    <style>.blue{background:blue;}</style>
</head>
<body ng-app="myApp" ng-controller="myCtrl"> 

    <p ng-class="{blue:present}">This is a paragraph. </p>

    <script>
        //Module declaration
        var app = angular.module('myApp',[]);
        //controller declaration
        app.controller('myCtrl', function($scope){
            $scope.present = false;
            $scope.colors = ['red','green','blue']; 
            angular.forEach($scope.colors, function(value, key){
                if(value == "green"){
                    $scope.present = true; 
                }
            });
        });
    </script>
</body> 
</html>

希望对你的问题有所帮助!