2
I have 2 filter buttons:
- Sort by Price - That Works.
- Sort by Category - Doesn’t Work.
I would like to operate the filter both by price and by category.
Both are modal and I’m doing it this way:
O Sort by price:
View section that calls the modal:
<!-- ORDENA POR PREÇO -->
<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>
Controller looks like this:
// 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
And the Filter, turning the screen like this:
<div class="card" ng-repeat="item in ofertass | orderBy: someModel" ng-init="$last ? fireEvent() : null" href="#/nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}" >
This part okay!
Now let’s get down to the problem?
To sort by category, I created a modal where I filter only the categories that are being shown to the user:
<ion-view view-title="Escolha as Categorias" hide-nav-bar="false" >
<ion-content>
<div class="button-bar">
<button class="button button-stable button-block icon-left ion-android-funnel" ng-click="userCategoria(categoria_comida_nome)">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="userCategoria()">Aplicar Filtro</button>
</div>
</ion-content>
</ion-view>
The controller of this modal is like this:
// 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);
$state.go("nhaac.promocoes");
}
// 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();
};
// 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
My call to this modal is like this:
<button class="button button-stable button-block icon-left ion-android-funnel"ng-model="someModel" ng-click="checkItems[item.categoria_comida_nome]" ui-sref="filtroPromo">Filtrar
</button>
It prints the selected categories on the console, but I’m not able to send this array back and apply to the filter, which is this way:
<div class="card" ng-repeat="item in ofertass | orderBy: someModel" ng-init="$last ? fireEvent() : null" href="#/nhaac/ofertas_singles/{{item.cadastra_oferta_cod_oferta}}" >
The Doubt: How can I filter, both by Category and Price? What I’m doing wrong?
JUST TO ILLUSTRATE 100%, FOLLOW THE ENTIRE CONTROLLER AND THEN THE ENTIRE MAIN VIEW:
.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);
}
// APLICANDO FILTRO CATEGORIA
$scope.userCategoria = function(checkItems) {
console.log("entra na chamada");
// $scope.userCategoria = $scope.checkItems(function(element) {
$scope.checkItems;
console.log("Imprime array");
console.log($scope.checkItems);
// };
// console.log("Imprime array");
// console.log($scope.userCategoria);
$scope.modal.hide();
$state.go("nhaac.ofertas_restaurante");
};
$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);
$state.go("nhaac.promocoes");
}
// 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();
};
// 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;
})
THE MAIN VIEW
<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">
<ion-refresher pulling-text="Puxe para atualizar..." on-refresh="doRefresh()"></ion-refresher>
<ion-list class="list card">
<div class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="search" ng-model="q" placeholder="Procurar" aria-label="filter restaurantess" />
</div>
</ion-list>
<div class="button-bar">
<!-- FILTRA POR... -->
<!-- <button class="button button-stable button-block icon-left ion-android-funnel" ng-click="abreModal()">Filtrar</button> -->
<!-- <a class="button button-stable button-block icon-left ion-android-funnel" ng-model="someModel" options="checkItems[item.categoria_comida_nome]" ui-sref="filtroPromo">Filtrar</a> -->
<button class="button button-stable button-block icon-left ion-android-funnel"ng-model="someModel" ng-click="checkItems[item.categoria_comida_nome]" ui-sref="filtroPromo">Filtrar
</button>
<!-- <button class="button button-stable button-block icon-left ion-android-funnel" >
Filtrar
</button> -->
<!-- ORDENA POR PREÇO -->
<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" 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"> Pedir Já </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>
Could put a content of
ofertass
as an example? This would help create a functional response.– OnoSendai
I’ll edit and put.
– Ramos
There, I put more details. Thank you.
– Ramos
In short, you want to order both by price and by category, being the most relevant price?
– Giovane
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!
– Sorack