AngularJS计数是/否值

时间:2015-08-13 14:26:37

标签: angularjs

我目前正在开发AngularJS / Parse.com网络应用程序

我想要实现的目标: 我想得到Y​​es&的总金额。数组中没有值。 例如是= 3否= 6

当前问题: 我已经设法得到所有的和&没有来自Parse的值并将它们放入数组中,但我无法计算是或否值的数量。

任何帮助/建议都会有所帮助!

HTML:

<md-card>
  <md-card-content>
    <canvas id="doughnut" class="chart chart-doughnut" data="widgetone_data" labels="widgetone_label"></canvas>
  </md-card-content>
  {{widgetone_data | json}}
</md-card>

控制器JS:

dashApp.controller("dashboardCtrl", function ($scope, $http, $filter) {
  $scope.parseRecommendations = [];
  $http({
      method : 'GET',url : 'https://api.parse.com/1/classes/Customers',
      headers: { 'X-Parse-Application-Id':'xxx', 'X-Parse-REST-API-Key':'xxx'}
  })
  .success(function(data, error) {
    $scope.parseResults = data.results;
    angular.forEach($scope.parseResults, function(results) {
      $scope.parseRecommendations.push(results.question_4_p1);
    });
  })
  .error(function(data, error) {alert('Failed, error code: ' + error.message);
  });

  // Recommend YES/NO
  var yesAmount = $filter('filter')($scope.parseRecommendations, { isSelected: 'yes' }).length;
  var noAmount = $filter('filter')($scope.parseRecommendations, { isSelected: 'no' }).length;
  $scope.widgetone_label = ["Yes", "No"];
  $scope.widgetone_data = [yesAmount,noAmount];
});

1 个答案:

答案 0 :(得分:0)

您可以使用 .filter() 方法。

此外,您犯了一个错误,因为您在实例化控制器时开始过滤数据,但您的API调用是异步,因此您必须将数据过滤到。 success()回调,否则您将过滤空数组

编辑:为了提高性能,您可以通过模拟 hashmap 来计算您的数量。见下文

   dashApp.controller("dashboardCtrl", function ($scope, $http, $filter) {
      $scope.parseRecommendations = [];

      var hashmap = {};

      $http({
          method : 'GET',url : 'https://api.parse.com/1/classes/Customers',
          headers: { 'X-Parse-Application-Id':'wmWxU64vx0QgKBiNQkx9jCDNO6UZDRrM6WkxAbTL', 'X-Parse-REST-API-Key':'0FHcBHZdeUJHKT8j0VQH0hQdN4TZ8qsOBxyd1rG3'}
      })
      .success(function(data, error) {
        $scope.parseResults = data.results;
        angular.forEach($scope.parseResults, function(results) {
          $scope.parseRecommendations.push(results.question_4_p1);
        });

        $scope.parseRecommendations.forEach(function(elm){
          hashmap.hasOwnProperty(elm)
          ? ++hashmap[elm]
          : hashmap[elm] = 1
        });

        //Filter yes
        var yesAmount = hashmap.yes;

        //Filter no
        var noAmount = hashmap.no;

        $scope.widgetone_label = ["Yes", "No"];
        $scope.widgetone_data = [yesAmount,noAmount];

        console.log($scope.widgetone_data);

      })
      .error(function(data, error) {alert('Failed, error code: ' + error.message);
      });
        });