如何计算包含特定值的行数?

时间:2016-08-31 08:55:03

标签: javascript jquery angularjs angular-datatables

我正在使用AngularJS,我有一个使用ng-repeat填充的表格。查看这个简短的例子:

http://jsfiddle.net/sso3ktz4/

如何查看具有特定值的行数?例如,在上面的小提琴中,如何用“second”这个词检查我有多少行?它应该返回“3”。

AngularJS答案是首选,尽管我也有JQuery可用。

谢谢!

2 个答案:

答案 0 :(得分:1)

更新的控制器代码如下,其中$ scope.findRowCount是必需的函数

var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);

function MyCtrl($scope) {
    $scope.items = [{
        name: 'first',
        examples: [{
            name: 'first 1'
        }, {
            name: 'first 2'
        }]
    }, {
        name: 'second',
        examples: [{
            name: 'second'
        }, {
            name: 'second'
        }]
    }];


    $scope.findRowCount=function(value){

    var count=0;
    angular.forEach($scope.items, function(item, i){
    if(item.name==value){

      count=count+1;


    }
    angular.forEach(item.examples, function(exp, j){

    if(exp.name==value){

      count=count+1;


    }

    })




    });
    console.log("count"+count);
    return count;
    }

    var result=$scope.findRowCount("second");
    console.log(result);
}

http://jsfiddle.net/p3g9vyud/

答案 1 :(得分:1)

试试这种方式



var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);

function MyCtrl($scope) {
    $scope.items = [{
        name: 'first',
        examples: [{
            name: 'first 1'
        }, {
            name: 'first 2'
        }]
    }, {
        name: 'second',
        examples: [{
            name: 'second'
        }, {
            name: 'second'
        }]
    }];
  //Get sum based on the label
  $scope.getTotalByLabel = function(keyword)
  {
    $scope.totalSecond = 0;
    angular.forEach($scope.items, function(value, key) {
        if(value.name == keyword)
        {
          $scope.totalSecond += 1;
        }
        angular.forEach(value.examples, function(val, k) {
          if(val.name == keyword)
          {
            $scope.totalSecond += 1;
          }
        });
    });
    return $scope.totalSecond;
  }
}

th,
td {
    padding: 7px;
    text-align: left;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <table border="1">
        <tbody ng:repeat="i in items">
            <tr>
                <td>{{i.name}}</td>
                <td>{{$index}}</td>
            </tr>
            <tr ng:repeat="e in i.examples">
                <td>{{e.name}}</td>
                <td>{{$index}}</td>
            </tr>
        </tbody>
    </table>
    <b>Total of second</b>: {{getTotalByLabel('second')}}
</div>
</div>
&#13;
&#13;
&#13;