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

2019-06-22 16:48发布

问题:

I want to do something like:

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

from a ng-class, so I tried:

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

But doesn't worked, throws an error

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

回答1:

For arrays you'd use indexOf, not in, which is for objects

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

so

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


回答2:

Look at the following code:

<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>

Hope, it helps your problem!