javascript - How to Filter by Category via Modal using checkbox Ionic / Angularjs? -


i have 3 types of filters:

one of research:

<div class="bar bar-subheader bar-assertive">     <label class="item-input-wrapper textbox-search">         <i class="icon ion-search placeholder-icon"></i>         <input ng-model="q" placeholder="procurar" aria-label="filter restaurantess" />     </label> </div> 

where ng-model filter is: | filter: q

one per order by:

<!-- order -->             <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..." has-search="true">ordenar                 <div class="option">                     <h2>{{option.name}}</h2>                 </div>             </button> 

where filter is: | orderby: somemodel

and need category filter, opens modal listing categories, showing categories listed (for user not waste time selecting category not exist in list), view of modal is:

<ion-modal view-title="cadastrar" hide-nav-bar="false"> <ion-header-bar>     <h1 class="title">choice categories</h1> </ion-header-bar> <ion-content>      <div class="card">         <div class="item item-text-wrap">             estão sendo listadas apenas categorias existentes em sua localização.         </div>     </div>      <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' track $index" ng-model="filtro[$index]" ng-true-value="{{item}}" ng-false-value="" ng-checked="check">{{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> 

as in following image, the result of modal code:

modal view result

ordering , search working well.

but i'm not getting way filter categories selected user.

to illustrate better, follows complete view (html) of main listing want filter categories:

   <ion-view side="center" view-title="vovócooks">   <!-- botÃo carrinho de compras --> <ion-nav-buttons side="right" class="has-header">     <a href="#/nhaac/carrinho" class="button button-clear button-icon icon ion-ios-cart"> {{total}} </a>      <button class="button button-icon button-clear ion-ios-color-filter-outline" id="menu-popover" ng-click="popover.show($event)"></button>  </ion-nav-buttons>  <center>     <div class="bar bar-subheader bar-assertive">         <label class="item-input-wrapper textbox-search">             <i class="icon ion-search placeholder-icon"></i>             <input ng-model="q" placeholder="procurar" aria-label="filter restaurantess" />         </label>     </div> </center>   <div class="tabs-striped tabs-top tabs-background-assertive tabs-color-light">     <div class="tabs" style="height:70px;">         <a class="tab-item active" href="#/nhaac/promocoes">             <i class="icon ion-home"></i> delÍcias caseiras         </a>         <a class="tab-item" href="#/nhaac/restaurantes">             <i class="icon ion-star"></i> vovÓs online         </a>     </div> </div>    <div class="tabs-striped tabs-color-assertive" >     <div class="tabs">         <a class="tab-item active" ng-click="dorefresh()">             <i class="icon ion-refresh"></i> atualizar         </a>          <a ng-show="checarpermissoes('logado_usuario')" class="tab-item" href="#/nhaac/perfil">             <i class="icon ion-person"></i> meu perfil         </a>     </div> </div>  <ion-content delegate-handle="top" lazy-scroll id="page-promocoes" class="has-header page-promocoes">      <ion-refresher pulling-text="puxe para atualizar..." on-refresh="dorefresh()"></ion-refresher>       <div class="list animate-fade-slide-in-right">          <div class="spacer" style="width: 300px; height: 65px;"></div>              <div class="card" >                   <div class="item" style="white-space:normal;font-size:12px">                       <center>                       <b>sua localização atual é: </b> {{endereco_atual}}                       </center>                     </div>                         <center>                           <button class="button button-clear button-assertive" style="font-size:12px" ui-sref="nhaac.localiza">                               mudar localização                           </button>                       </center>                </div>                <div class="button-bar">              <!-- filter category... -->             <button class="button button-stable button-block  icon-left ion-android-funnel" ng-click="abremodal()">                 filtrar             </button>               <!-- order -->             <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..." has-search="true">ordenar                 <div class="option">                     <h2>{{option.name}}</h2>                 </div>             </button>          </div>            <div class="card" ng-repeat="item in ofertass | filter:q | orderby:somemodel | unique: 'cadastra_oferta_cod_oferta'" 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" ng-src="{{item.cadastra_oferta_foto}}" />                 <div class="promocao"><b>{{item.cadastra_oferta_desconto}}% off</b></div>                 <div class="desconto"><b>{{item.cadastra_oferta_valor_com_desconto | currency}}</b></div>                  <div class="item">                     <center>                         <h2 style="white-space:normal; color:#d95b43;"><b>{{item.cadastra_oferta_titulo_promocao}}</b></h2>                     </center>                 </div>                  <div class="spacer" style="width: 300px; height: 8px;"></div>                  <h3><b>vovó cozinheira: </b>{{item.fornecedores_fantasia}}</h3>                  <div ng-model="item.avaliacao_media">                      <div ng-show="item.avaliacao_media">                         <!--                            <h4>avaliação média:  {{item.avaliacao_media}} </h4> -->                           <h4>avaliação média                              <span class="stars alignleft">                         <span ng-style="{ 'width': getstars(item.avaliacao_media) }">                     </span></h4>                        </div>                          <div class="spacer" style="width: 300px; height: 8px;"></div>                      <div class="item">                         <h3>categoria: {{item.categoria_comida_nome}}</h3>                          <h3><small><b>descrição: </b>{{item.cadastra_oferta_descricao}}</small></h3>                          <h3>                             preço normal: <s style="color:red;"><small class="preco"> {{item.cadastra_oferta_valor_sem_desconto | currency}}</small></s><br> preço promocional: <small class="preco"> {{item.cadastra_oferta_valor_com_desconto | currency}} </small><br> preço frete: <small class="preco"> {{item.fornecedor_configura_frete_custo_padrao | currency}} </small>                          </h3>                       </div>                 </div>             </div>               <a class="item button button-clear button-assertive ink" href="#nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}"><b>pedir</b></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-content> <!-- ./content --> 

in controller, i try filter ng-click excerpt this:

// pega os itens selecionados na modal e coloca num array     $scope.checkitems = {};      $scope.print = function () {         console.log($scope.checkitems);     }      // aplicando filtro categoria     $scope.usercategoria = function (checkitems) {         console.log("entra na chamada");          $scope.modal.hide();       };      $scope.save = function (checkitems) {         console.log("chamou o save");         var array = [];         (i in $scope.checkitems) {             console.log($scope.checkitems[i]);             if ($scope.checkitems[i] == true) {                 array.push(i);              }         }         console.log(array);          $scope.meufiltro = array;          console.log("selecionado final: "+ $scope.meufiltro);           window.localstorage.setitem("filtros", array);          $scope.modal.hide();     } 

this pretty messed many tests i've done ...

but can see data, , store locally separated commas:

console result

that is, i suffering return (ignorance) ...

if post | groupby: 'mais_campo' gives error.

i can´t make filter categories, , need help.

or need change logic? not know if lack of better logic (or knowledge). would appreciate ...

well, finish, make available my entire controller:

     .controller("promocoesctrl", function ($scope, $rootscope, $state, $ionicscrolldelegate, $http, $httpparamserializer, $stateparams, $timeout, $ionicloading, $ionicpopup, $ionicpopover, $ionicslideboxdelegate, $ionichistory, ionicmaterialink, ionicmaterialmotion, $ionicmodal, sharedcartservice, sharedfilterservice) {          $ionichistory.nextviewoptions({             disableback: false,             historyroot: true         });           //put cart after menu         var cart = sharedcartservice.cart;          $scope.endereco_atual = window.localstorage.getitem("endereco_atual");          if (window.localstorage.getitem("user_des") === undefined) {             console.log("usuário logado, setar como logado");            } else {              console.log("usuário deslogado, setar como deslogado");             var setar = "user_des";             window.localstorage.setitem("user_des", setar)         };           $scope.getstars = function (avalia) {             // value             var val = parsefloat(avalia);             // turn value number/100             var size = val / 6 * 100;             return size + '%';         }          $scope.cadastra_oferta_cod_fornecedor = $stateparams.cadastra_oferta_cod_fornecedor;          $scope.endereco_atual = window.localstorage.getitem("endereco_atual");           // ordena por...         $scope.selectablenames = [              {                 name: "por preço: menor para o maior",                 role: "+cadastra_oferta_valor_com_desconto"         },              {                 name: "por preço: maior para o menor",                 role: "-cadastra_oferta_valor_com_desconto"         },              {                 name: "por maior desconto (%)",                 role: "-cadastra_oferta_desconto"         },              {                 name: "menor prazo de entrega",                 role: "+fornecedor_configura_frete_prazo_entrega_min"         },              {                 name: "maior prazo de entrega",                 role: "-fornecedor_configura_frete_prazo_entrega_min"         },              {                 name: "oferta em ordem alfabética",                 role: "+cadastra_oferta_titulo_promocao"         },              {                 name: "por categoria",                 role: "+categoria_comida_nome"         },    //        { //            name: "por menor valor de frete", //            role: "+fornecedor_configura_frete_custo_padrao" //        },      ];           $scope.getopt = function (option) {             return option.name + ":" + option.role;             console.log(option);             window.localstorage.setitem("ordenapor", 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);         }          // aplicando filtro categoria         $scope.usercategoria = function (checkitems) {             console.log("entra na chamada");              $scope.modal.hide();           };          $scope.save = function (checkitems) {             console.log("chamou o save");             var array = [];             (i in $scope.checkitems) {                 console.log($scope.checkitems[i]);                 if ($scope.checkitems[i] == true) {                     array.push(i);                  }             }             console.log(array);              $scope.meufiltro = array;              console.log("selecionado final: "+ $scope.meufiltro);               window.localstorage.setitem("filtros", array);              $scope.modal.hide();         }             // inicia filtro por categoria             $ionicmodal.fromtemplateurl('/templates/filters/side-filter.html', {             scope: $scope,             animation: 'slide-in-up'         }).then(function (modal) {             $scope.modal = modal;         });         $scope.abremodal = function () {             $scope.modal.show();         };         $scope.closemodal = function () {             $scope.modal.hide();           };          // fim filtro por categoria            $rootscope.page_id = "promocoes";          $scope.endereco_atual = window.localstorage.getitem("endereco_atual");           $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          $scope.endereco_atual = window.localstorage.getitem("endereco_atual");          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 = [];                 (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));                             $state.reload();                             $scope.$state = $state;                         }                     }                     $scope.ofertass = [];                     (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.removebackview();                         $ionichistory.clearcache();                         //    $ionichistory.clearhistory();                         $state.reload();                         $scope.$state = $state;                       }                 }                 $scope.ofertass = [];                 (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/>problema: com tabela de ofertas",                 });             }).finally(function () {                 $scope.$broadcast("scroll.refreshcomplete");                 // event done, hidden animation loading                 $timeout(function () {                     $ionicloading.hide();                 }, 500);             });            };           if (data_ofertass === null) {             data_ofertass = [];         };          //coloca produto em destaque         $scope.addtostar = function (id, image, name, price, supply_id, deliver) {              console.log(id);             console.log(name);             console.log(price);             console.log(supply_id);             };           //add cart function         $scope.addtocart = function (id, image, name, price, supply_id, deliver, entrega) {             // chama cart.add de services              window.localstorage.setitem("fonecedor_carrinho", supply_id);             window.localstorage.setitem("tipos_pagamentos", tipopag);             window.localstorage.setitem("frete", deliver);             window.localstorage.setitem("faz_entrega", entrega);             cart.add(id, image, name, price, 1, supply_id, deliver);             $state.go('nhaac.carrinho');          };          // animation readmore         var fetchitems = function () {             (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");         };            var tipo = '';          // $scope.checarpermissoes();          $scope.checarpermissoes = function (tipo) {             var permitido;              if (tipo === 'logado_usuario' && window.localstorage.getitem("user_log") !== null) {                 permitido = true;             } else {                 permitido = false;             }              return permitido;         };             // 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;     }) 

thank time. sorry english...

edit:

i think wrong here:

   <div class="card" ng-repeat="item in ofertass | filter:q | orderby:somemodel | unique: 'cadastra_oferta_cod_oferta'" ng-init="$last ? fireevent() : null" href="#/nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}"> 

because now can array like: ["temakes", "cozinha vegetariana"]

but, how add more filter in ng-repeat? array called meufiltro:

$scope.save = function (checkitems) {             console.log("chamou o save");             var array = [];             (i in $scope.checkitems) {                 console.log($scope.checkitems[i]);                 if ($scope.checkitems[i] == true) {                     array.push(i);                  }             }             console.log(array);              $scope.meufiltro = array;              window.localstorage.setitem("filtros", array);              $scope.modal.hide();         } 

i not able understand complete problem.

but can try use selected variable in category, when user selects category, turned true.

and in section want show hide, use filter | selected


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -