2016-04-22 40 views
3
纳克级

我想做的事情是这样的:从ng-class
如何检查,如果事情是在阵列从

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

,所以我尝试:

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

但没有按” t工作,抛出错误

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

回答

4

对于数组你会使用indexOf,不in,这是对象

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

所以

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

现在是正确的:),+1 – alexmac

+0

感谢它的工作! :) –

+0

'ng-class =“list.indexOf(this.id)!== -1?'class-1':'class-2'”' –

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> 

希望,它可以帮助您的问题!