31

次のようなオブジェクトの配列があります。

$scope.students = [{'isSelected': true},
    {'isSelected': true},
    {'isSelected': false},
    {'isSelected': true},
    {'isSelected': true},
]

isSelectedプロパティが に設定されているカウント項目を取得するにはどうすればよいtrueですか?

アップデート:

問題は$scope.students、REST API からフェッチされ、$scope.students 変数を単純にループしても、変数がundefinedリクエストが完了するまで機能しないため、ループ コードで$scope.students is not defined.

使用してみ$watchましたが、その場合は watch ディレクティブの下でループを定義する必要があり、$scope.students が定義されているときに 1 回だけ機能し、その後は $scope.students 自体が変更されていないためループが機能しません。

4

3 に答える 3

27

これを行う別の方法があります: AngularJS フィルターです。これを書くことができます:

var selectedCount = $filter('filter')($scope.students, { isSelected: true }).length;
于 2014-11-17T13:52:10.560 に答える
21

JavaScript フィルター メソッドを使用することもできます ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filterを参照) 。

$scope.selectedStudentsCount = function() {
  return $scope.students.filter(function(obj){return obj.isSelected}).length;
}
于 2016-04-04T10:57:14.043 に答える
19

次のメソッドをコントローラーに追加できます。selectedStudentsCountスコープ内の変数は、選択されたすべての学生の数を保持します(ここでisSelectedは に設定されていtrueます)。

で選択されたユーザーをカウントする関数は、が空でないangular.forEach場合にのみ実行されます。studentsそれ以外の場合、空の students変数selectedStudentsCountは を返し0ます。

$scope.selectedStudentsCount = function() {
    var count = 0;
    angular.forEach($scope.students, function(student){
        count += student.isSelected ? 1 : 0;
    });
    return count; 
}

selectedStudentsCountこれは関数であるため()、テンプレートで呼び出す必要があることに注意してください。

<h2>Total selected students: {{selectedStudentsCount()}}</h2>
于 2013-03-12T12:11:14.597 に答える