如何在Ionic Framework中计算选中的复选框字段?

时间:2016-08-09 12:21:56

标签: angularjs ionic-framework ionic-view

我创建了一个CheckBoxlist,用于从api获取数据,其中包含:

在控制器中:

$scope.bebidasextras = [];

var promise = $http.get('http://nhac.esy.es/api_carrinho/lista_bebida_extra.php?json=restaurantes')
  .success(function(retorno) {
    console.log(retorno);
    $scope.bebidasextras = retorno; // não precisa fazer retorno.data

        $scope.user = {
            bebidasextras: [$scope.bebidasextras[1]]
          };
          $scope.checkAll = function() {
            $scope.user.bebidasextras = angular.copy($scope.bebidasextras);
          };
          $scope.uncheckAll = function() {
            $scope.user.bebidasextras = [];
          };
          $scope.checkFirst = function() {
            $scope.user.bebidasextras = [];
            $scope.user.bebidasextras.push($scope.bebidasextras[0]);
          };
          $scope.setToNull = function() {
            $scope.user.bebidasextras = null;
          };

在视图中:

<ion-view view-title="Compra de Bebidas Adicionais" ng-controller="adbebidaCtrl" >

        

        <ion-checkbox ng-model="user.bebidasextra" > <h2>{{role.ad_bebida_titulo}}</h2> <p>R$ {{role.ad_bebida_valor}}</p></ion-checkbox>


    </ion-item>
</ion-list>

</ion-content>    

如何计算所选项目,当您选择完列表后,单击一个按钮并在本地存储所有数据,以便以后使用?

1 个答案:

答案 0 :(得分:1)

Theres a small fiddle可以解决您的问题。

<div ng-repeat="bebida in bebidasextras">
  <ion-checkbox ng-model="bebida.selected" > 
      <h2>{{bebida.ad_bebida_titulo}}</h2>     
      <p>R$ {{bebida.ad_bebida_valor}}</p>
  </ion-checkbox>
</div>
<h2>{{'Total R$ ' + getTotalSelected()}}</h2>
$scope.getTotalSelected = function() {
  var total = 0;

  for(var i = 0; i < $scope.bebidasextras.length; i++){
    var bebida = $scope.bebidasextras[i];
    total += bebida.selected ? Number(bebida.ad_bebida_valor) : 0;
  }

  return total;
}