How to checked radio button in IONIC? - angularjs

How to set checked/default radio button value in IONIC?
I have code like below:
<ul>
<li ng-repeat="quest in Questions">
{{quest.question}}
<div ng-repeat="choice in quest.jawaban" ng-init="answer[quest.no]='A'">
<input
type="radio"
ng-model="answer[quest.no]"
ng-value="'{{choice.pil}}~{{choice.jawaban}}'"
name="{{quest.no}}">
{{choice.jawaban}}
</div>
<br>
</li>
</ul>
ng-init="answer[quest.no]='A'"
I need replace 'A' to "selected" value from database simulate like below
$scope.Questions = [{"no":"1","qus_id":"AI1a","question":"Pilih buah kesukaan:","selected":"A","jawaban":[{"pil":"A","jawaban":"Pepaya"},{"pil":"B","jawaban":"Mangga"},{"pil":"C","jawaban":"Pisang"},{"pil":"D","jawaban":"Jambu"}]},{"no":"2","qus_id":"AI1b","question":"Warna Favorit:","selected":"B","jawaban":[{"pil":"A","jawaban":"Merah"},{"pil":"B","jawaban":"Kuning"},{"pil":"C","jawaban":"Hijau"},{"pil":"D","jawaban":"Biru"}]}];
};
To set default/checked radio button.
More details are available at http://play.ionic.io/app/6d698853ef09

just change your input line with the following code.
<input type="radio" ng-model="answer[quest.no]" value="{{choice.pil}}" name="{{quest.no}}">

ng-init="answer[quest.no]='A'"
You are using it wrong, value is actually different than A its A~Merah, so you should use it like
ng-init="answer[quest.no]='A~Merah'"
or best way is
<input type="radio" ng-model="answer[quest.no]" ng-value="'{{choice.pil}}'" name="{{quest.no}}">

In Ionic 2:
Project src directory: src => app => pages => home => home.ts
open home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
num1:number;
num2:number;
sum:string;
// deafult value checked
rdValue:string = "mPlus";
constructor(public alertCtrl: AlertController) {
}
doSum():void {
if(typeof this.num1 !== 'number' || typeof this.num2 !== 'number') {
this.presentAlert();
} else {
var localNum1 = parseInt(this.num1);
var localNum2 = parseInt(this.num2);
//this.sum = parseInt(this.num1) + parseInt(this.num2);
var copyValue = this.rdValue;
switch(copyValue) {
case 'mPlus':
this.sum = localNum1 + localNum2;
break;
case 'mMinus':
this.sum = localNum1 - localNum2;
break;
case 'mMulti':
this.sum = localNum1 * localNum2;
break;
case 'mDivide':
this.sum = localNum2 / localNum1;
break;
}
}
}
presentAlert() {
let alert = this.alertCtrl.create({
title: 'Warnning',
subTitle: 'Only Enter Integer',
buttons: ['OK']
});
alert.present();
}
}
home.html
<ion-header>
<ion-navbar color="primary">
<ion-title>MCalculator</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding="0">
<ion-item>
<ion-label color="primary">Number 1:</ion-label>
<ion-input type="text" placeholder="Enter First Number" [(ngModel)]="num1"></ion-input>
</ion-item>
<ion-item>
<ion-label color="primary">Number 2:</ion-label>
<ion-input type="text" placeholder="Enter Second Number" [(ngModel)]="num2"></ion-input>
</ion-item>
<ion-list radio-group class="btn-margin m-font-size" [(ngModel)]="rdValue">
<ion-list-header>
<p>Arithmetic Options<p>
</ion-list-header>
<ion-item>
<ion-label>Addition</ion-label>
<ion-radio checked="true" value="mPlus"></ion-radio>
</ion-item>
<ion-item>
<ion-label>Subtraction</ion-label>
<ion-radio value="mMinus"></ion-radio>
</ion-item>
<ion-item>
<ion-label>Multiplication</ion-label>
<ion-radio value="mMulti">Multiplication</ion-radio>
</ion-item>
<ion-item>
<ion-label>Addition</ion-label>
<ion-radio value="mDivide"></ion-radio>
</ion-item>
</ion-list>
<ion-item>
<ion-label color="primary">Result:</ion-label>
<ion-input type="text" placeholder="Result" [(ngModel)]="sum"></ion-input>
</ion-item>
<button ion-button full large class="btn-margin" (click)="doSum()">Submit Operation</button>
</ion-content>
<!-- <ion-footer>
<ion-toolbar color="primary">
<ion-title></ion-title>
</ion-toolbar>
</ion-footer> -->

Related

Ionic scroll with direction y is not working in ionic 1

view code:
<ion-view class="forms-view" ng-init="loadall()">
<ion-nav-buttons side="left">
<button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<ion-nav-title>
<span>List</span>
</ion-nav-title>
<ion-content>
<ion-scroll direction="xy" on-scroll="addMoreItem()">
<ion-list ng-controller="card">
<div class="item item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" ng-model="input.filterUser" placeholder="Search" style="height:48px;">
</label>
</div>
<ion-item class="item-avatar item-icon-right" ng-repeat="cardlists in cardlist | filter:input.filterUser" ui-sref="app.details({card_id:cardlists.card_id,xyz:0})">
<img src="{{cardlists.avatar}}" >
<h2>{{cardlists.name}}</h2>
<p>{{cardlists.card_id}} </p>
<i class="icon ion-plus-round custom-icon" ng-show="!cardlists.isShow" ng-click="addTo(cardlists.card_id);cardlists.isShow = true"></i>
<i class="icon ion-checkmark-round" ng-show="cardlists.isShow"></i>
</ion-item>
</ion-list>
</ion-scroll>
</ion-content>
</ion-view>
controller code:
controller('boardCtrl', function ($scope, $http, $cordovaSQLite, $localStorage, $state,$rootScope,$ionicPlatform,$ionicPopup,$timeout,$filter,$ionicNavBarDelegate) {
$rootScope.limit_list=10;
$scope.addMoreItem=function()
{
if($scope.cardlist.length >= $rootScope.limit_list)
{
$rootScope.limit_list+=5;
}
$scope.loadall();
}
$scope.loadall=function()
{
$rootScope.cardlist = [];
var query2 = "SELECT * FROM abc LIMIT "+$rootScope.limit_list;
$cordovaSQLite.execute(db, query2, []).then(function (res) {
if (res.rows.length > 0) {
for (var j = 0; j < res.rows.length; j++) {
var name = res.rows.item(j).name;
$rootScope.cardlist.push({
name: name,
age: res.rows.item(j).age,
card_id: res.rows.item(j).card_id,
avatar: "img/avatar5.png"
});
}
}
}
}
}
I want to display a list whenever view is loaded and its working fine.The only change what i want to make is to display only 10 names by default and once i scroll down the page i want to load 10 more and so on.The above code is working perfectly fine but only in x direction i.e horizontal scroll.I want it load more name once i scroll down side i.e vertical scroll.Can any one tell me what is the issue with above code.It will be helpful.

ionic1 angular js ng-repeat | filter : search not working?

angular.module('starter.services', [])
.factory('Chats', function($http) {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats=[];
$http({
method: 'GET',
url: 'js/champions.json'
}).then(function success(data) {
for (var i = 1; i < 700; i++) {
if (data.data.data[i]!=undefined) {
chats.push(data.data.data[i]) ;
//console.log(data.data.data[i]);
}
}
});
//console.log(chats);
return {
all: function() {
return chats;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
}) ;
<ion-view view-title=" Tüm Kahramanlar">
<ion-content>
<ion-list>
<ion-item>
<ion-label fixed>Arama</ion-label>
<input type="text" style="width: 100%" placeholder="Karakter Adına Göre Filtrele" ng-model="search" ></input>
</ion-item>
</ion-list>
<ion-list>
<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats | orderBy : 'key' | filter : search " type="item-text-wrap" href="#/tab/chats/{{chat.id}}">
<img ng-src="http://ddragon.leagueoflegends.com/cdn/7.18.1/img/champion/{{chat.image.full}}">
<h2>{{chat.name }}</h2>
<p>{{chat.title}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
<ion-option-button class="button-assertive" ng-click="remove(chat)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
Guys , How can ı filter this ng repeat code its coming like nothing happened. so its not filtered . please help me :( ı think its model think not changed when ı am write | filter : 'NameSomething' its Working but ı cant get in there ng model how can ı do this :?
Try like this :
Change this line : (Make sure you define $scope.search = {}; in controller)
<input type="text" style="width: 100%" placeholder="Karakter Adına Göre Filtrele" ng-model="search.name" ></input>
Simple Implementation :
Search with name:
<input type="text" ng-model="searchData.name">
<div ng-repeat="chat in chats | filter:searchData"> {{chat.name}}</div>
Working Demo :
https://plnkr.co/edit/t6B6fZDRCSLuBN36GLVD?p=preview

Angularjs multiple functions

I have 2 buttons:
One scans a QR code and returns the values which works.
Another on the same page that confirms the input values, but I cannot get the second function to fire.
I have 2 inputs, deviceid and companyid, and 2 buttons. The scan button, via ng-click, calls scanQR and the second button, also via ng-click, calls checkBlanks.
A confirm ID button calls a functions to firstly check for blanks then alert the user if the input data is missing. Once the 2 inputs have content it will save the data via the verifyDetails() call. But I cannot get the checkBlanks function to run.
HTML Code is:-
<ion-view title="Settings">
<ion-content padding="true" class="has-header">
<form class="list">
<label class="item item-input" name="deviceid">
<span class="input-label">Device ID</span>
<input type="text" placeholder="" ng-model="deviceid">
</label>
<label class="item item-input" name="companyid">
<span class="input-label">Company ID</span>
<input type="text" placeholder="" ng-model="companyid">
</label>
</form>
<button ng-click="scanQR()" class="button button-positive button-block">Scan QR to Configure</button>
<button ng-click="checkBlanks()" class="button button-positive button-block">Confirm ID</button>
<form class="list">
<ion-toggle toggle-class="toggle-positive" ng-checked="true">Vibrate</ion-toggle>
<ion-toggle toggle-class="toggle-positive">Light on Scan</ion-toggle>
<div style="text-align:center;" class="show-list-numbers-and-dots">
<p style="color:#000000;font-size:10px;">On Android devices set to off and use the volume controls to turn the flashlight on or off.</p>
</div>
<ion-radio ng-model="radioCheck" value="security">Security</ion-radio>
<ion-radio value="utilities">Utilities</ion-radio>
</form>
</ion-content>
</ion-view>
AngularJS is:-
function($scope, $stateParams) {
$scope.radioCheck = "security";
$scope.scanQR = function() {
cordova.plugins.barcodeScanner.scan(
function(result) {
var TagResponse = result.text;
var config = TagResponse.indexOf("Config:");
if (TagResponse !== '') {
if (config === 0) {
var ConfigVals = TagResponse.split(':');
$scope.deviceid = ConfigVals[1];
$scope.companyid = ConfigVals[2];
$scope.$apply();
}
}
});
};
$scope.checkBlanks = function() {
alert("Device ID" + $scope.deviceid);
console.log("Device ID" + $scope.device)
if ($scope.deviceid === '') {
alert("Please enter a device ID", Dismissed, "Error");
} else if ($scope.companyid === '') {
alert("Please enter a Company ID", Dismissed, "Error");
} else {
verifyDetails();
}
};
}
Any help appreciated, I'm very new to Angularjs and Ionic.

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.;
});
}

Angular update screen

This question is asked all over the place but no combination of $timeout, $scope.$apply etc is making any difference.
$scope.checkCameraIP = function(i){
if(i > 99)
return;
var ip2Check = $deviceIP.substr(0, $deviceIP.lastIndexOf(".")+1) + i;
if(ip2Check != $deviceIP)
Gitup.get(ip2Check, gitupCmds.getDiskSpace).then(function (response) {
$scope.cameras.some(function (camera,index) {
if (camera.ip == '192.168.100.0') {
$timeout(function(){
camera.ip = ip2Check;
camera.class = 'ion-wifi balanced'; // I JUST WANT THIS TO SHOW UP!
// $scope.checkCamera(camera);
})
}
camerasFound ++;
if(camerasFound < $scope.cameras.length)
$timeout(function(){$scope.checkCameraIP(ipRange++)},100);
return true;
});
},function(){$scope.checkCameraIP(ipRange++)}).catch(function(e){
console.log(e);
});
else
$scope.checkCameraIP(ipRange++);
}
I'm looping through IP addressses looking for cameras. When I find one I update it with the IP address on an array
$scope.cameras = [{
name: '1',
ip: '192.168.100.0',
class: 'ion-alert-circled',
connected: false
}, {
name: '2',
ip: '192.168.100.0',
class: 'ion-alert-circled',
connected: false
}]
This is shown on a list
<ion-list ng-controller="CamerasCtrl">
<ion-item ng-repeat="camera in cameras">
<label class="item item-input">
<i class="icon ion-camera placeholder-icon"></i>{{camera.name}} -
<input type="text" class="block" ng-model="camera.ip" ng-change="onCameraIPChange(camera)" placeholder="{{camera.ip}}">
<i id="connected" ng-class="camera.class"></i>
</label>
<div class="col text-right">
<button ng-show="camera.connected && camera.files" class="button icon ion-android-delete" ng-click="formatCamera(camera)">
Format camera
</button>
</div>
</ion-item>
</ion-list>
I can find the cameras fine and set their data - but for the life of me I can't get the list to update on the screen.
This is running in an Ionic App on Android.
Any solutions please help!!
It seems it was because the button was outside of the scope of the controller. While it was calling the function, it wasn't updating the scopes data.
<ion-list ng-controller="CamerasCtrl">
<button class="button-block icon ion-search" ng-click="searchForCameras()">
Find Cameras
</button>
<ion-item ng-repeat="camera in cameras">
<label class="item item-input">
<i class="icon ion-camera placeholder-icon"></i>{{camera.name}} -
<input type="text" class="block" ng-model="camera.ip" ng-change="onCameraIPChange(camera)" placeholder="{{camera.ip}}">
<i id="connected" ng-class="camera.class"></i>
</label>
<div class="col text-right">
<button ng-show="camera.connected && camera.files" class="button icon ion-android-delete" ng-click="formatCamera(camera)">
Format camera
</button>
</div>
</ion-item>
</ion-list>
Fixed it

Resources