Extract objects in Ionic

Asked

Viewed 1,043 times

1

I’m trying to get the selected data from a Checkbox in the Ionic.

My View is like with the CheckBox:

<ion-view view-title="Comprar Bebidas Adicionais" hide-nav-bar="false">

    <div class="bar bar-subheader">
        <h2 class="title">{{'Sub-Total R$ ' + getTotalSelected() }}</h2>
    </div>

    <ion-content delegate-handle="top" lazy-scroll id="lista-bebidas" class="has-header lista-bebidass" ng-controller="exBebidasCtrl">

        <ion-refresher pulling-text="Puxe para atualizar..." on-refresh="doRefresh()"></ion-refresher>
        <ion-list class="card list">
            <div class="item item-input">
                <i class="icon ion-search placeholder-icon"></i>
                <input type="search" ng-model="q" placeholder="Procurar" aria-label="filter bebidasextras" />
            </div>
        </ion-list>

        <ion-list>

            <div ng-repeat="bebida in bebidasextras">
                <ion-checkbox ng-model="bebida.selected" ng-checked="bebida.selected">
                    <h2>{{bebida.ad_bebida_titulo}}</h2>
                    <p>R$ {{bebida.ad_bebida_valor}}</p>
                </ion-checkbox>
            </div>

        </ion-list>

        <button class="button button-block button-balanced" ng-click="updateBebida()">
                        Continuar Comprando
                    </button> {{ selectedItems | json }}

    </ion-content>

</ion-view>

This JSON I’m printing on the screen just to see if it really caught.

And mine Controller is like this:

.controller("exBebidasCtrl", function($scope, $rootScope, $state, $ionicScrollDelegate, $http, $httpParamSerializer, $stateParams, $timeout, $ionicLoading, $ionicPopup, $ionicPopover, $ionicSlideBoxDelegate, $ionicHistory, ionicMaterialInk, ionicMaterialMotion, sharedCartService, CartServiceBebidasEx, $location, DBLocal) {

            // VERIFICA SE HÁ BEBIDAS EXTRAS

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



                    // CALCULA TOTAL DOS ITENS SELECIONADOS NA LISTA
                    $scope.sub = function(i) {
                        i.quantity--;
                    }

                    $scope.add = function(i) {
                        i.quantity++;
                    }

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

                })
                .error(function(erro) {
                    console.log(erro);
                });


            // PEGA BEBIDAS SELECIONADAS      
            $scope.updateBebida = function() {
                var p = [];
                for (var i = 0; i < $scope.bebidasextras.length; i++) {
                    var item = $scope.bebidasextras[i];
                    console.log(item);
                    if (item.selected) {
                        p.push(item)
                    }

                }

                $scope.selectedItems = p;
                console.log(p);

                var titulo = data.filter(function(e) {
                    return e.titulo_promo == p.ad_bebida_titulo
                    conlole.log(titulo);
                })


                // TESTA SE GUARDA A BEBIDA SELECIONADA

                // INSERINDO DADOS LOCALMENTE
                DBLocal.localdb();

                //            var len = $scope.p.ad_bebida_titulo;
                //            console.log(len);

                //          var dados =  p.filter(function(e){
                //              return e.ad_bebida_titulo == bebida.ad_bebida_titulo;
                //          })

                DBLocal.db.transaction(function(res) {
                    res.executeSql("INSERT INTO AD_BEBIDAS (nome_bebida_ad) VALUES(?);", [p.ad_bebida_titulo]);
                });



            }

(A bit messy, but I commented) Note that I want to store the data from checkbox selected in a WEBSQL, but I’m not able to take it, see his console:

Console com os dados

I do not know how to take the dice of this object to play in my local database. Ali in:

DBLocal.db.transaction(function(res){
    res.executeSql("INSERT INTO AD_BEBIDAS (nome_bebida_ad) VALUES(?);",[p.ad_bebida_titulo]);  

How can I get this data?

  • First thing I realized is that in your view you have ng-model="bebida.selected" but in the controller I only found $scope.bebidasextras. Until I saw that having a variable drink var bebida = $scope.bebidasextras[i]; but this variable bebida is not in the $scope, therefore invisible/inaccessible to your view.

  • But you are listing the products on View, I have added drink.Selected due to ng-repeat: ng-repeat="drink in bebidasextras"

  • It’s even capturing what was selected, but I don’t know how to catch the Bjects, as in the image.

  • Bad ai did not see ng-repeat, passed beaten. It would not be because the variable p is an array? Soon p. ad_bebida_titulo does not exist, but p[0].ad_bebida_titulo exists.

  • Exactly that! Thank you Neuber!

  • I added in response to make life easier for those who arrive later.

Show 1 more comment

1 answer

3


Your variable pis an array.

Here in this code snippet

DBLocal.db.transaction(function(res){
          res.executeSql("INSERT INTO AD_BEBIDAS (nome_bebida_ad) VALUES(?);", [p.ad_bebida_titulo]);              
});

You’re trying to access the property ad_bebida_titulo of the object Array, as it does not exist you end up getting a undefined.

To make it work it would have to be something like:

// PEGA BEBIDAS SELECIONADAS      
$scope.updateBebida = function() {
    var p = [];
    for (var i = 0; i < $scope.bebidasextras.length; i++) {
        var item = $scope.bebidasextras[i];
        console.log(item);
        if (item.selected) {
            p.push(item)
        }

    }

    $scope.selectedItems = p;
    var item;

    //aqi vai percorrer todo o conteudo da vriavep p, poderia ate dar
    //uma otimaizada e deixar junto com o p.push(item), ai "economiza" um for
    for(var i in p){
        item = p[i];
        console.log(item);
        var titulo = data.filter(function(e) {
            return e.titulo_promo == item.ad_bebida_titulo
            conlole.log(titulo);
        })


        // TESTA SE GUARDA A BEBIDA SELECIONADA

        // INSERINDO DADOS LOCALMENTE
        DBLocal.localdb();

        DBLocal.db.transaction(function(res) {
            res.executeSql("INSERT INTO AD_BEBIDAS (nome_bebida_ad) VALUES(?);", [item.ad_bebida_titulo]);
        });
    }
}
  • 1

    Thank you very much Neuber!

  • Neuber, just one more question, if I can help...

  • Here you are only taking the first one you select in the checkboxes, how can I find everyone who is picking up in the Checkbox?

  • I edited the answer see there, I think now it is easier to understand

  • In "var title = data.filter(Function(e) { " the "date" would be "p"? I wonder why it was not defined...

  • That’s right. I switched the filter with the p...

  • But it continues to register only 1 record. If the user chooses more than one, it sends only the last selected.

  • Hi Neuber, I decided to change the scheme of screens that was not working well, I opened a new post, que apesar de parecido é diferente... Follow the link if you can help. http://answall.com/questions/149472/addir-itens-ao-banco-data

  • Guys, thank you! I’m just coming back to thank you. Thanks anyway! :))

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.