How to Filter with Two Conditions using Modal in Ionic

Asked

Viewed 517 times

1

I created a modal that filters only the categories that are registered, now I would like to take the selected items in the Checkbox of this modal and filter according to the categories selected by the user, I am not knowing how to make this filter:

My modal:

    <ion-modal-view>
  <ion-header-bar>
    <h1 class="title">Escolha as Categorias</h1>
  </ion-header-bar>
  <ion-content>

        <div class="button-bar">    
            <button class="button button-stable button-block  icon-left ion-android-funnel" ng-click="save()">Aplicar Filtro</button>
        </div>

    <ion-list>
      <ion-checkbox ng-repeat="item in ofertass | unique:'categoria_comida_nome'" ng-model="checkItems[item.categoria_comida_nome]" ng-change="print()">{{item.categoria_comida_nome}}</ion-checkbox>
    </ion-list>

    <div class="button-bar">    
        <button class="button button-stable button-block  icon-left ion-android-funnel" ng-click="save()">Aplicar Filtro</button>
    </div>


  </ion-content>
</ion-modal-view>

My View where I call the modal:

<ion-view view-title="Promoções" hide-nav-bar="false" >
    <!-- content -->

    <!-- BOTÃO CARRINHO DE COMPRAS -->
        <ion-nav-buttons side="right"   >           
                <a  href="#/nhaac/carrinho" class="button button-icon icon ion-android-cart" > {{total}} </a>               
        </ion-nav-buttons>

    <ion-content delegate-handle="top" lazy-scroll  id="page-promocoes" class="has-header page-promocoes">

        <div class="button-bar">      

                 <!-- FILTRA POR... -->
                 <button class="button button-stable button-block  icon-left ion-android-funnel" ng-click="openModal()">
                     Filtrar           
                 </button>               


                <!-- ORDENA POR -->
                <button class="button button-stable button-block  icon-left ion-android-restaurant" modal-select="" ng-model="someModel" options="selectableNames" option-property="role" modal-title="Ordenar por...">Ordenar
                <div class="option">
                      <h1>{{option.name}}</h1>
                </div>
               </button>              

        </div>

        <div class="list animate-fade-slide-in-right">

            <div class="card" ng-repeat="item in ofertass | orderBy:someModel or " ng-init="$last ? fireEvent() : null" href="#/nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}" >                    

                <div class="item item-thumbnail-top item-text-wrap">
                    <img class="imagemCapa" image-lazy-loader="lines" image-lazy-src="{{item.cadastra_oferta_foto}}"/>
                    <div class="promocao"><b>{{item.cadastra_oferta_desconto}}% OFF</b></div>
                    <div class="desconto"><b>Apenas: R$ {{item.cadastra_oferta_valor_com_desconto}}</b></div>

                    <div class="item"><h2><b>{{item.cadastra_oferta_titulo_promocao}}</b></h2></div>

                    <div class="item">
                        <h3>Categoria: {{item.categoria_comida_nome}}</h3>
                        <h3>
                            Preço Normal: <s><small class="preco">R$ {{item.cadastra_oferta_valor_sem_desconto}}</small></s><br>
                            Preço Promocional <small class="preco">R$ {{item.cadastra_oferta_valor_com_desconto}} </small>
                      </h3>         
                        <div class="to_trusted" ng-bind-html="item.cadastra_oferta_descricao"></div>
                    </div>    
            </div>

                <div>
                    <center><p style="position:relative;right:10px;bottom:0px;top:1px">
                            <a  ng-click="addToCart(item.cadastra_oferta_cod_oferta,item.cadastra_oferta_foto, item.cadastra_oferta_titulo_promocao,item.cadastra_oferta_valor_com_desconto)" class="button button-assertive button-clear icon-left ion-android-cart"> Comprar </a> 
                    </p></center>
                </div>


                <a class="item button button-clear button-dark ink" href="#nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}">MAIS INFORMAÇÕES</a>
            </div>
        </div>
        <ion-list class="list">
        <ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="onInfinite()" distance="5px" ng-if="hasMoreData"></ion-infinite-scroll>
        </ion-list>

        <ion-list class="list">
            <div class="item" ng-if="results.length == 0" >
                <p>Nenhum resultado encontrado...</p>
            </div>
        </ion-list>


        <ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="10%">
        <ion-infinite-scroll-content loadingSpinner="bubbles">
    </ion-infinite-scroll>



    </ion-content>
    <!-- ./content -->
</ion-view>

I wanted to add the category filter together with the sort filter that already exists:

<div class="card" ng-repeat="item in ofertass | orderBy:someModel or " ng-init="$last ? fireEvent() : null" href="#/nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}" >    

To finish this is the controller with the modal:

 .controller("promocoesCtrl", function($scope,$rootScope,$state,$ionicScrollDelegate,$http,$httpParamSerializer,$stateParams,$timeout,$ionicLoading,$ionicPopup,$ionicPopover,$ionicSlideBoxDelegate,$ionicHistory,ionicMaterialInk,ionicMaterialMotion,$ionicModal, sharedCartService,sharedFilterService){

    //put cart after menu
    var cart = sharedCartService.cart;

    // ORDENA POR...
    $scope.selectableNames =  [
    {name : "Por preço: Do Menor para o Maior", role : "+cadastra_oferta_valor_com_desconto"}, 
    { name : "Por preço: Do Maior para o Menor", role : "-cadastra_oferta_valor_com_desconto"},    
  ];


    $scope.getOpt = function(option){     
        return option.name + ":" + option.role;          
    };  
    // FIM DE ORDENA POR


    // PEGA OS ITENS SELECIONADOS NA MODAL E COLOCA NUM ARRAY
    $scope.checkItems = { };

    $scope.print = function() {
        console.log($scope.checkItems);
    }

    $scope.save = function() {
        var array = [];
        for(i in $scope.checkItems) {
            console.log($scope.checkItems[i]);
            if($scope.checkItems[i] == true) {
                array.push(i);
            }
        }
        console.log(array);
    }


    // INICIA FILTRO POR CATEGORIA    
      $ionicModal.fromTemplateUrl('/templates/filters/side-filter.html', {
        scope: $scope,
        animation: 'slide-in-up'
      }).then(function(modal) {
        $scope.modal = modal;
      });
      $scope.openModal = function() {
        $scope.modal.show();
      };
      $scope.closeModal = function() {
        $scope.modal.hide();
      };
      // Cleanup the modal when we're done with it!
      $scope.$on('$destroy', function() {
        $scope.modal.remove();
      });
      // Execute action on hide modal
      $scope.$on('modal.hidden', function() {
        // Execute action
      });
      // Execute action on remove modal
      $scope.$on('modal.removed', function() {
        // Execute action
      });
    // FIM FILTRO POR CATEGORIA


    $rootScope.page_id = "promocoes" ;
    $scope.scrollTop = function(){
        $ionicScrollDelegate.$getByHandle("top").scrollTop();
    };
    // open external browser 
    $scope.openURL = function($url){
        window.open($url,"_system","location=yes");
    };
    // open AppBrowser
    $scope.openAppBrowser = function($url){
        window.open($url,"_blank","closebuttoncaption=Done");
    };
    // open WebView
    $scope.openWebView = function($url){
        window.open($url,"_self");
    };

    // Set Motion
    $timeout(function(){
        ionicMaterialMotion.slideUp({
            selector: ".slide-up"
        });
    }, 300);

    var targetQuery = ""; //default param
    var raplaceWithQuery = "";
    // TODO: Dinamics Promoções
    targetQuery = "json=promocao"; //default param
    raplaceWithQuery = "json=promocao";


    var fetch_per_scroll = 1;
    // animation loading 
    $ionicLoading.show({
        template: '<div class="loader"><svg class="circular"><circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/></svg></div>'
    });


    $scope.noMoreItemsAvailable = false; //readmore status
    var lastPush = 0;
    var data_ofertass = [];

    if(window.localStorage.getItem("data_ofertass") !== "undefined"){
        data_ofertass = JSON.parse(window.localStorage.getItem("data_ofertass"));
            if (data_ofertass !== null){
            $scope.ofertass = [];
            for(lastPush = 0; lastPush < 10; lastPush++) {
                if (angular.isObject(data_ofertass[lastPush])){
                    $scope.ofertass.push(data_ofertass[lastPush]);
                };
            }
            $timeout(function() {
                $ionicLoading.hide();
            }, 500);
        }
    }
    if(!angular.isObject(data_ofertass)){
        $timeout(function() {
        // retry retrieving data
        $http.get("http://vovocooks.com.br/admin/apis/api_listagem/lista_oferta_api.php?json=promocao".replace(targetQuery,raplaceWithQuery)).then(function(response) {
            data_ofertass = response.data;
            if(typeof(Storage) != "undefined"){
                try {
                    window.localStorage.setItem("data_ofertass",JSON.stringify(data_ofertass));
                } catch(e) {
                    window.localStorage.clear();
                    window.localStorage.setItem("data_ofertass",JSON.stringify(data_ofertass));
                    $ionicHistory.clearCache();
                    $ionicHistory.clearHistory();
                    $state.reload();
                    $scope.$state = $state;
                }
            }
            $scope.ofertass = [];
            for(lastPush = 0; lastPush < 100; lastPush++) {
                if (angular.isObject(data_ofertass[lastPush])){
                    $scope.ofertass.push(data_ofertass[lastPush]);
                };
            }
        },function(response) {
            // error message
            var alertPopup = $ionicPopup.alert({
                title: "error " + response.status,
                template: response.statusText + "<br/>problem: table ofertas",
            });
        }).finally(function() {
            $scope.$broadcast("scroll.refreshComplete");
            // event done, hidden animation loading
            $timeout(function() {
                $ionicLoading.hide();
            }, 1000);
        });

        }, 1000);
    }   


    $scope.doRefresh = function(){
        // retry retrieving data
        window.localStorage.clear();
        $http.get( "http://vovocooks.com.br/admin/apis/api_listagem/lista_oferta_api.php?json=promocao".replace(targetQuery,raplaceWithQuery)).then(function(response) {
            data_ofertass = response.data;
            if(typeof(Storage) != "undefined"){
                try {
                    window.localStorage.setItem("data_ofertass",JSON.stringify(data_ofertass));
                } catch(e) {
                    window.localStorage.clear();
                    window.localStorage.setItem("data_ofertass",JSON.stringify(data_ofertass));
                    $ionicHistory.clearCache();
                    $ionicHistory.clearHistory();
                    $state.reload();
                    $scope.$state = $state;
                }
            }
            $scope.ofertass = [];
            for(lastPush = 0; lastPush < 100; lastPush++) {
                if (angular.isObject(data_ofertass[lastPush])){
                    $scope.ofertass.push(data_ofertass[lastPush]);
                };
            }
        },function(response) {
            // error message
            var alertPopup = $ionicPopup.alert({
                title: "error " + response.status,
                template: response.statusText + "<br/>problem: table ofertas",
            });
        }).finally(function() {
            $scope.$broadcast("scroll.refreshComplete");
            // event done, hidden animation loading
            $timeout(function() {
                $ionicLoading.hide();
            }, 500);
        });

    };


    if (data_ofertass === null){
        data_ofertass = [];
    };



    //add to cart function
     $scope.addToCart=function(id,image,name,price){    
        // CHAMA CART.ADD DE SERVICES 
        cart.add(id,image,name,price,1);    

     };   





    // animation readmore
    var fetchItems = function() {
        for(var z=0;z<fetch_per_scroll;z++){
            if (angular.isObject(data_ofertass[lastPush])){
                $scope.ofertass.push(data_ofertass[lastPush]);
                lastPush++;
            }else{;
                $scope.noMoreItemsAvailable = true;
            }
        }
        $scope.$broadcast("scroll.infiniteScrollComplete");
    };

    // event readmore
    $scope.onInfinite = function() {
        $timeout(fetchItems, 500);
    };

    // create animation fade slide in right (ionic-material)
    $scope.fireEvent = function(){
        ionicMaterialMotion.fadeSlideInRight();
        ionicMaterialInk.displayEffect();
    };


    // animation ink (ionic-material)
    ionicMaterialInk.displayEffect();
    $scope.rating = {};
    $scope.rating.max = 5;
})

How to place this array in the existing filter and having two conditions?

I don’t know if it’s clear, but I’m having a hard time.

For these filters I am using the Angular Filter: https://github.com/a8m/angular-filter

  • Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!

1 answer

1


// bota aqui o nome de propriedade de categoria no objeto 'oferta'
<input type="search" ng-model="filtro.nome_categoria" />


<div class="card" ng-repeat="item in ofertass | filter: filtro | orderBy:someModel or " ng-init="$last ? fireEvent() : null" href="#/nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}" >

This will sort the array and filter by the name of the selected category.

  • Perfect! Thank you! :)))

Browser other questions tagged

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