Search code examples
angularjsionic-frameworkionic-view

How Calculate fields Selected Checkbox in Ionic Framework?


I created a CheckBoxlist for get data from an api, with:

IN a CONTROLLER:

$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;
          };

In a View:

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

How can I go by calculating the selected items and when you finish choosing the list, click a button and store all data locally, to be used later?


Solution

  • Theres a small fiddle that can solve your problem.

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