【问题标题】:How to check if something is in array from ng-class如何检查ng-class的数组中是否有东西
【发布时间】:2016-04-22 20:14:25
【问题描述】:

我想做类似的事情:

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

【问题讨论】:

    标签: javascript angularjs ng-class


    【解决方案1】:

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

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

    所以

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

    【讨论】:

    • ng-class="list.indexOf(this.id) !== -1 ? 'class-1' : 'class-2' "
    【解决方案2】:

    看下面的代码:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-12
      • 2012-06-04
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      相关资源
      最近更新 更多