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

感情迁移 提交于 2019-12-23 08:56:09

问题


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!



来源:https://stackoverflow.com/questions/36802586/how-to-check-if-something-is-in-array-from-ng-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!