How to add badge to cart in ionic? - angularjs

I am developing e-commerce shopping app with ionic,angular i am a beginner my cart is working fine but i want to add a badge which shows quantity am not able to do it.
Here is my cart controller
.controller('cartCtrl', function($scope,$rootScope,sharedCartService,$ionicPopup,$state,$http) {
$scope.cart=sharedCartService.cart_item; // Loads users cart
$scope.get_qty = function() {
$scope.total_qty=0;
$scope.total_amount=0;
}
//onload event-- to set the values
$scope.$on('$stateChangeSuccess', function () {
$scope.cart=sharedCartService.cart;
$scope.total_qty=sharedCartService.total_qty;
$scope.total_amount=sharedCartService.total_amount;
});
//remove function
$scope.removeFromCart=function(c_id){
$scope.cart.drop(c_id);
$scope.total_qty=sharedCartService.total_qty;
$scope.total_amount=sharedCartService.total_amount;
};
$scope.inc=function(c_id){
$scope.cart.increment(c_id);
$scope.total_qty=sharedCartService.total_qty;
$scope.total_amount=sharedCartService.total_amount;
};
$scope.dec=function(c_id){
$scope.cart.decrement(c_id);
$scope.total_qty=sharedCartService.total_qty;
$scope.total_amount=sharedCartService.total_amount;
};
$scope.checkout=function(){
if($scope.total_amount>0){
$state.go('checkOut');
}
else{
var alertPopup = $ionicPopup.alert({
title: 'No item in your Cart',
template: 'Please add Some Items!'
});
}
};
Menu from where user adds product to cart
<ion-list ng-repeat="item in menu_items">
<ion-item class="item-thumbnail-left" >
<img ng-src="{{'img/'+ item.p_image_id +'.jpg'}}" ng-click="showProductInfo(item.p_id,item.p_description,item.p_image_id,item.p_name,item.p_price)" >
<p style="position:absolute;right:10px;">
<a ng-click="addToCart(item.p_id,item.p_image_id,item.p_name,item.p_price)" class="button button-balanced button-clear icon ion-android-cart"> </a>
</p>
<h2 ng-click="showProductInfo(item.p_id,item.p_description,item.p_image_id,item.p_name,item.p_price)" > {{item.p_name}} </h2>
<p ng-click="showProductInfo(item.p_id,item.p_description,item.p_image_id,item.p_name,item.p_price)">Price: ₹ {{item.p_price}}</p>
</ion-item>
</ion-list>

Related

Change button color after success callback function is executed in Ionic/Angular 2

First of all I am a programming noob, I am trying to build an ionic app for sending commands to arduino via bluetooth.
<ion-content padding>
<div padding>
<div ion-button clear block medium>
<a ion-button color="energetic" outline full (click)="tab=1" [outline]="tab==2"> Slider</a>
<a ion-button color="danger" full [outline]="tab==1" (click)="tab=2"> Position</a>
</div>
</div>
<div [hidden]="tab==2">
<ion-card>
<ion-card-header text-center>
<h2>Turn Light ON/OFF</h2>
</ion-card-header>
<ion-card-content>
<div text-center>
<button ion-button icon-left color="primary" round (click)="toggle()" large>
<ion-icon name="ios-sunny-outline"></ion-icon>
ON/OFF
<ion-icon name="sunny"></ion-icon>
</button>
</div>
<ion-list>
<ion-item>
<ion-label> OFF/ON </ion-label>
<ion-toggle checked="false" (ionChange)="toggle()"></ion-toggle>
</ion-item>
</ion-list>
</ion-card-content>
</ion-card>
</div>
<div [hidden]="tab==1">
<div text-center>
<button ion-button icon-left color="dark" round outline (click)="Enable()">
<ion-icon name="bluetooth" color="danger"></ion-icon>
Show Bluetooth List
</button>
</div>
<ion-card>
<ion-list *ngFor="let list of lists">
<button ion-item (click)="connect(list.address)">
<ion-icon name="bluetooth" item-left></ion-icon>
{{list.name}}
</button>
</ion-list>
</ion-card>
<ion-card>
<ion-card-header text-center color="danger">
Status
</ion-card-header>
<ion-card-content text-center>
{{status}}
</ion-card-content>
</ion-card>
</div>
</ion-content>
This function iterate through the paired devices and whenever I click on particular button/device, connect() function is fired, and on connection a success call back function is excuted.
#Component({
selector: 'page-home',
templateUrl: 'home.html',
})
export class HomePage {
constructor(public navCtrl: NavController) {
}
public tog: any = 'OFF';
public tab= 1;
toggle() {
switch (this.tog) {
case 'ON':
this.Write('OFF');
this.tog = 'OFF';
break;
case 'OFF':
this.Write('ON');
this.tog = 'ON';
default:
break;
}
}
status : any;
lists : any ;
Enable(){
BluetoothSerial.isEnabled().then((data)=> {
this.status = 'Bluetooth is ON';
BluetoothSerial.list().then((allDevices) => {
this.lists = allDevices;
});
BluetoothSerial.discoverUnpaired().then((devices)=>{
this.lists.push(devices);
this.status= 'discovered some devices';
}).catch((err)=> { this.status= 'No devices were found'; });
}).catch((error)=>{ this.status='Bluetooth is not turned on'; });
}
connect(mac){
BluetoothSerial.connect(mac).subscribe((success)=>{
this.status= 'Bluetooth connection is successful with'+ success;
});
}
Write (msg){
BluetoothSerial.write(msg).then( res =>{
this.status = ' This has been written :' + res;
}).catch(res=> function(){
this.status = ' This has not been written :' + res;
});
}
}
Problem : .subscribe does not update this.status variable on view,unless I switch to other page and come back to it again.
Request : I would like to show user that connection to their selected device has been done by changing the color of selected button. In addition while It is connecting to bluetooth device, I would like show some sort of notification that it is connecting to device please wait? How I can implement this?
I would deeply appreciate any help !!
Thanks
For the waiting notification you need to implement the loadingController (placed in your code within connect() function).
For the button color,
My suggestion: You should use your array lists to create another array deviceListWithStatus:Array<any> in that array push each object from the lists {device:[a device object from the list],status:[the assoc status value]}.
status : any;
lists : any ;
deviceListWithStatus:Array<any>;
Enable(){
deviceListWithStatus = [];
BluetoothSerial.isEnabled().then((data)=> {
this.status = 'Bluetooth is ON';
BluetoothSerial.list().then((allDevices) => {
for(let i in allDevice){
deviceListWithStatus.push({device:allDevice[i],status:'disconnected'})
}
});
BluetoothSerial.discoverUnpaired().then((devices)=>{
for(let i in devices){ deviceListWithStatus.push({device:devices[i],status:'disconnected'})
}
this.status= 'discovered some devices';
}).catch((err)=> { this.status= 'No devices were found'; });
}).catch((error)=>{ this.status='Bluetooth is not turned on'; });
}
Then in your html template:
<ion-list *ngFor="let dev of deviceListWithStatus">
<button ion-item [ngStyle]="(dev.status=='connected')?{'background-color': 'green'}:{'background-color': 'red'}" (click)="connect(dev)">
<ion-icon name="bluetooth" item-left></ion-icon>
{{dev.device.name}}
</button>
</ion-list>
Then change your connect function such as this:
connect(dev){
let loading = this.loadingCtrl.create({
content: 'Please wait...'
});
loading.present();
BluetoothSerial.connect(dev.device.address).subscribe((success)=>{
loading.dismiss();
dev.status = 'connected';
this.status= 'Bluetooth connection is successful with'+ success.;
});
}

Add change amount and change the Total in Check Box in Ionic

I created a list in Checkbox, listing products where the user can choose a product. I need add in the product list an option where the user can change the quantity of products selected. How I can do it?
My View:
<ion-view view-title="Bebidas Adicionais" ng-controller="exBebidasCtrl" >
<div class="bar bar-subheader">
<h2 class="title">{{'Sub-Total R$ ' + getTotalSelected()}}</h2>
</div>
<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" >
<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">
<a ng-click="addToCart(bebida.ad_bebida_titulo,bebida.ad_bebida_valor)" class="button button-assertive button-clear icon ion-android-cart"> Continuar Comprando </a>
</button>
</ion-content>
My 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;
};
$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);
});
You can have an input box having a + and - button. Clicking upon which user can change the quantity of product selected.
If you can share some more details probably I would be able to answer in a better way.

How to open a modal in a div which already has a controller (AngularJs)

<ion-list>
<ion-item>
<div id="result_1" class="result">
<p class="title" ng-repeat="item in result | filter: query">
<span class="ic"><b>{{item.name}}</b></span>
Click for details...
</p>
<div class="clear"></div>
</div>
</ion-item>
</ion-list>
this is a part of my first Ionic project, i'm new in this framework and AngularJs, so I have a controller which searchs for data in a json file.
I need to open a modal when user clicks on
Click for details...
but when I searched about it, I figured out that I need another controller for creating a modal.
I already have a controller in my whole page, how can I add another controller to that specific line? Or do you know any other way to create a modal without using another controller?
<ion-item>
<div id="result_1" class="result">
<p class="title" ng-repeat="item in result | filter: query">
<span class="ic"><b>{{item.name}}</b></span>
<br>
<br>
<span ng-click="popUp()" class="ic1">Click for details...</span>
</p>
<div class="clear"></div>
</div>
</ion-item>
script:
using $ionicPopup
$scope.popUp = function() {
var alertPopup = $ionicPopup.alert({
title: 'More Details...',
template: 'decription', // templateUrl:'myModalContent.html'
buttons: [{
text: '<b>OK</b>',
type: 'button-assertive'
}]
});
};
check this link for Details
using Ui bootstrap
$scope.popUp = function() {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html'
resolve: {
data: function() {
return $scope.data;
}
}
});
}
There are many options you can pass. You can give a controller for your pop up too.
check this link for ui.bootstrap.modal

Ionic Material Content not load

I am using ionic with agular js and ionic material framework. I used YouTube api for getting YouTube channel feed, but its content are not getting load initially. When i scroll down, feed data are getting display.
Link of image for initally content not getting load.
http://i.hizliresim.com/DR4ZPy.jpg
Link of image when i scroll down
http://i.hizliresim.com/7bMzNm.jpg
Ionic console logs error.
TypeError: o[0] is undefined /lib/ionic-material/ionic.material.min.js, Line: 13
Code snippet of my HTML file "Gallery.Html"
Galery CTRL
.controller('GalleryCtrl', function($scope, $stateParams, $timeout, ionicMaterialInk, ionicMaterialMotion, $http) {
// Set Motion
$scope.$parent.showHeader();
$scope.$parent.clearFabs();
$scope.isExpanded = false;
$scope.$parent.setExpanded(false);
$scope.$parent.setHeaderFab(false);
$timeout(function() {
ionicMaterialMotion.slideUp({
selector: '.slide-up'
});
}, 300);
$timeout(function() {
ionicMaterialMotion.fadeSlideInRight({
startVelocity: 3000
});
}, 700);
// Activate ink for controller
ionicMaterialInk.displayEffect();
$scope.videos = [];
$scope.playerVars = {
rel: 0,
showinfo: 0,
modestbranding: 0,
}
$scope.nextPageToken = null;
$scope.youtubeParams = {
key: 'AIzaSyAurmOD4QgzS5jBxca1KMUe_GWGuxV6C5Q',
type: 'video',
maxResults: '5',
part: 'id,snippet',
q: 'necatiakcay',
order: 'date',
channelId: 'UCpdJQ9OrynGRA110wHO2_iA',
}
function loadVideos(params, callback) {
$http.get('https://www.googleapis.com/youtube/v3/search', {params: params}).success(function(response){
var videos = [];
if(response.nextPageToken) {
$scope.nextPageToken = response.nextPageToken;
console.log ($scope.nextPageToken);
angular.forEach(response.items, function(child){
videos.push(child);
});
}
callback(videos);
});
}
$scope.loadOlderVideos = function() {
var params = $scope.youtubeParams;
if ($scope.nextPageToken) {
params['pageToken'] = $scope.nextPageToken;
}
loadVideos(params, function(olderVideos){
if (olderVideos) {
$scope.videos = $scope.videos.concat(olderVideos);
}
$scope.$broadcast('scroll.infiniteScrollComplete');
});
};
$scope.loadNewerVideos = function() {
var params = $scope.youtubeParams;
params['pageToken'] = '';
loadVideos(params, function(newerVideos) {
$scope.videos = newerVideos;
$scope.$broadcast('scroll.refreshComplete');
});
};
<ion-view view-title="Gallery">
<ion-content>
<ion-refresher
pulling-text="Yükleniyor..."
on-refresh="loadNewerVideos()">
</ion-refresher>
<div class="list slide-up">
<div id="aktif" ng-repeat="video in videos track by video.id.videoId" style="width: 100%; margin: 0px;" class="card card-gallery item item-text-wrap">
<div class="ink dark-bg">
<h2>{{video.snippet.title}}</h2>
<p>{{video.snippet.publishedAt | limitTo: 10}}</p>
<div class="embed-responsive embed-responsive-16by9">
<youtube-video class="embed-responsive-item" video-id="video.id.videoId" player-vars="playerVars"></youtube-video>
</div>
</div>
<div class="tabs tabs-icon-left static">
<a style="max-width: 100%;" class="tab-item stable-bg assertive">
<i class="icon ion-heart"></i>
4
</a>
<a style="max-width: 100%;" class="tab-item stable-bg assertive">
<i class="icon ion-heart"></i>
4
</a>
<a style="max-width: 100%;" class="tab-item stable-bg positive-900">
<i class="icon ion-chatbubbles"></i>
2
</a>
</div>
</div>
<ion-infinite-scroll
on-infinite="loadOlderVideos()"
distance="30%">
</ion-infinite-scroll>
</ion-content>
</ion-view>

ng-show doesn't reveal instantly but on page change?

I have this code to show loading message.
<ion-view title="Rooms">
<ion-content>
<ion-list ng-show="rooms">
<ion-item class="item-icon-left" ng-repeat="room in rooms" type="item-text-wrap" ng-click="openChatRoom(room.id)">
<i class="icon {{room.icon}}"></i>
<h2>{{room.name}}</h2>
</ion-item>
</ion-list>
<ion-list ng-hide="rooms.length">
<ion-item class="textCenter">
<i class="icon ion-loading-c"></i> Loading Rooms
</ion-item>
</ion-list>
</ion-content>
What it does now is just showing "loading Rooms" for awhile and nothing shows up.
But when I change page and return to this page again, items in ng-show just shows up and never show "loading Rooms" again.
So why this ng-show doesn't reveal instantly? Below are its controllers
.controller('RoomsCtrl', function($scope, Rooms, Chats, $state, $ionicModal) {
//console.log("Rooms Controller initialized");
$scope.rooms = Rooms.all();
console.log($scope.rooms);
$scope.openChatRoom = function (roomId) {
$state.go('app.chat', {
roomId: roomId
});
};
})
.factory('Rooms', function ($firebase) {
// Might use a resource here that returns a JSON array
var ref = new Firebase(firebaseUrl);
var rooms = $firebase(ref.child('rooms')).$asArray();
return {
all: function () {
return rooms;
},
get: function (roomId) {
// Simple index lookup
return rooms.$getRecord(roomId);
}
}
});

Resources