如何检查某些内容是否来自ng-class

时间:2016-04-22 20:14:25

标签: javascript angularjs 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 ...

2 个答案:

答案 0 :(得分:9)

对于数组,您使用indexOf,而不是in,这是用于对象

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

所以

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

答案 1 :(得分:0)

请查看以下代码:

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

希望,它可以帮到你解决问题!