I just want to ask how can I update the dynamic textfield upon a button click? The textfield is dynamic and the value should come from observable.
Code Behind
var observableModule = require("data/observable");
var source = new observableModule.Observable();
var HomePage = function() {};
HomePage.prototype = new BasePage();
HomePage.prototype.constructor = HomePage;
HomePage.prototype.contentLoaded = function(args) {
var page = args.object;
source.textSource = "sample";
var layout = page.getViewById("stackID");
var textField = new TextFieldModule.TextField();
var textFieldBindingOptions = {
sourceProperty: "textSource",
targetProperty: "text",
twoWay: false
};
textField.bind(textFieldBindingOptions, source);
layout.addChild(textField);
}
HomePage.prototype.buttonTap = function() {
source.textSource = "new word";
source.update();
}
XML
<stack-layout loaded="contentLoaded" id="stackID">
<Button tap="buttonTap" text="Update" />
</stack-layout>
I was able to find on how to update the source on click.
HomePage.prototype.onTap = function() {
source.set("textSource", "new word");
}
Source: http://docs.nativescript.org/cookbook/data/observable
Related
I have implemented the following CardIO plugin in my Ionic App:
https://github.com/card-io/card.io-Cordova-Plugin
This works fine on iOS. However, on Android, when I use the keyboard option in the Camera Screen to manually type in the card details, it first loads the correct screen momentarily, and then jumps back to the first screen (Sign Up screen in this case) of the app. While debugging the app flow, I saw that the callback for Card IO is working fine, but there seems to be an issue when Ionic handles the event.
Any help greatly appreciated!
Following is the code in my controller:
$scope.$on('$ionicView.beforeEnter', function()
{
$scope.creditCardScanning();
}
$scope.creditCardScanning = function(){
var cardIOResponseFields = [
"cardType",
"redactedCardNumber",
"cardNumber",
"expiryMonth",
"expiryYear",
"cvv",
"postalCode"
];
var onCardIOComplete = function(response) {
for (var i = 0; i < cardIOResponseFields.length; i++) {
var field = cardIOResponseFields[i];
}
var cardName = response[cardIOResponseFields[0]].toUpperCase();
for (i = 0; i < $scope.cardtype.length; i++) {
var cardTypeDict = $scope.cardtype[i];
if(cardTypeDict.card_type_name === cardName){
document.getElementById('cardtype').selectedIndex = i;
$scope.params.card_type = cardName;
break;
}
}
document.getElementById('cardNumber').value = response[cardIOResponseFields[2]];
$scope.params.card_number = response[cardIOResponseFields[2]];
var expMonthVal = response[cardIOResponseFields[3]];
for(i=0;i < $scope.expmonth.length; i++) {
var expMonthDict = $scope.expmonth[i];
if(expMonthDict.value === expMonthVal){
document.getElementById('expmonth').selectedIndex = i;
$scope.params.expiration_month = expMonthDict.value;
break;
}
}
for (i = 0; i < $scope.expyear.length; i++) {
var expYearDict = $scope.expyear[i];
if(expYearDict.value === response[cardIOResponseFields[4]]){
document.getElementById('expyear').selectedIndex = i;
$scope.params.expiration_year = response[cardIOResponseFields[4]];
break;
}
}
document.getElementById('cvv').value = response[cardIOResponseFields[5]];
$scope.params.security_code = response[cardIOResponseFields[5]];
};
var onCardIOCancel = function() {
console.log("card.io scan cancelled");
};
var onCardIOCheck = function (canScan) {
console.log("card.io canScan? " + canScan);
var scanBtn = document.getElementById("scanBtn");
if (!canScan) {
console.log("Cannot scan card");
}
scanBtn.onclick = function (e) {
CardIO.scan({
"requireExpiry": true,
"requireCVV": true,
"requirePostalCode": false,
"shows_first_use_alert": true,
"disable_manual_entry_buttons": false
},
onCardIOComplete,
onCardIOCancel
);
}
};
CardIO.canScan(onCardIOCheck);
}
And in my view, I am calling the function to load the next page, once the card details are successfully entered and the "Next" Button is tapped.
I want to create a OList, so that every position opened a new OList if I tap on it. At this moment I have following code:
function readCustomerSuccessCallback(data, response) {
var citems = [];
for (var i = 0; i < data.results.length; i++) {
var citem = new sap.m.StandardListItem(
{
type: "Active",
tap : readProducts(data.results[i].STATION_ID),
title: data.results[i].CUSTOMER_NAME,
description: data.results[i].STATION_ID
});
citems.push(citem);
}
var oList = new sap.m.List({
headerText : "Customers",
setGrowingScrollToLoad: true,
items : citems,
press: function(e) {
console.log(oList.getSelectedItems());
}
});
oList.placeAt("content"); // place model onto UI
}
function readProducts(category) {
console.log("read request started");
startTime = new Date();
if (!haveAppId()) {
return;
}
sURL = myUrl;
var oHeaders = {};
oHeaders['Authorization'] = authStr;
//oHeaders['X-SMP-APPCID'] = appCID; //this header is provided by the logon plugin
var request = {
headers : oHeaders,
requestUri : sURL,
method : "GET"
};
OData.read(request, readProductsSuccessCallback, errorCallback);
}
The function read CustomerSuccesCAllback creates a OList,and if I tap on a field of this list, I want that a new List shows up. For the second step is the function readproducts responsible.
With this code it doesnt work. It shows me not the customers, but only theyre details.
Has anybody an idea?
Change in readCustomerSuccessCallback:
tap: function(e){
readProducts(this.getDescription),
}
//this will stop invoking the function while defining your items
Google api Autocomplete does not work in mobile but work perfectly in browser in ionic framework. In mobile it take auto value on long press but not on just tap.
`var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, options);
var autocompleteto = new google.maps.places.Autocomplete(inputto,options);
google.maps.event.addListener(autocompleteFrom, 'place_changed', function() {
var place = autocompleteFrom.getPlace();
$rootScope.fromLat = place.geometry.location.lat();
$rootScope.fromLng = place.geometry.location.lng();
$rootScope.from = place.formatted_address;
$scope.placesfrom = $rootScope.from;
fromlat = $rootScope.fromLat;
fromlng = $rootScope.fromLng;
/*var googlemaphome = document.getElementById('googlemap-home');
var Map = new google.maps.Map(googlemaphome,mapOptions);
var posfrom = new google.maps.LatLng(fromlat,fromlng);
var frommarker = new google.maps.Marker({
icon: 'img/marker.png',
position: posfrom,
});
frommarker.setMap(Map);
Map.setCenter(posfrom);
$scope.Map = Map;*/
var Mapoptions ={
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
zoomControl:false,
draggable:true,
mapTypeControl:false,
scaleControl:false,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true
}
var bounds = new google.maps.LatLngBounds();
var googlemaphome = document.getElementById('googlemap-home');
var Map = new google.maps.Map(googlemaphome,Mapoptions);
var marker;
var markers = [
[fromlat,fromlng],
[28.6328,77.2197]
];
for(var i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
icon: 'img/marker.png',
map: Map
});
}
Map.fitBounds(bounds);
x=1;
checkstatus();
$scope.$apply();
});
google.maps.event.addListener(autocompleteto, 'place_changed', function() {
var place = autocompleteto.getPlace();
$rootScope.toLat = place.geometry.location.lat();
$rootScope.toLng = place.geometry.location.lng();
$rootScope.to = place.formatted_address;
$scope.placesto = $rootScope.to;
tolat = $rootScope.toLat;
tolng = $rootScope.toLng;
y=1;
checkstatus();
$scope.$apply();
});
$scope.oncurrent = function(){
$rootScope.currentpoint = currentpos;
$rootScope.currentflag = 1;
$scope.startpoint = currentpos;
$scope.placesfrom = currentpos;
geocoder.geocode( { 'address': currentpos}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK){
$rootScope.currentlat = results[0].geometry.location.lat();
$rootScope.currentlng = results[0].geometry.location.lng();
}
});
x=1;
checkstatus();
};
`
Be sure that you allow google api communication. Perhaps the request to google are blocked.
Maybe the transfer restriction are stronger on your device than in your browser
Install whitelist plugin with
ionic plugin add https://github.com/apache/cordova-plugin-whitelist.git
Then add this line to your config.xml(It is recommonded to add the specific URL, but for test case it's easier to allow everything)
<access origin="*"/>
And depends on usecase it is necessary to set the correct Content-Security-Policy in the header part of your index.html. But I think this isn't necessary in your situation.
<meta http-equiv="Content-Security-Policy" content=".....">
Below is my example that I have. So far it does the following.
Enter in 3 values to a row
Retrieve all the values from all rows on load
Place all the values from each row and print them to screen that was
retrieved from the above step.
The part that I need help with is trying to find all the values of one row based on a value that exists in that row.
If a row contains the values name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ I would like to get all the data of that row when some one searches for ‘Andrew’
So far if you look at the function ‘searchItems’ you will see that I am trying to find data based on the value of the search input. The problem I am having is all I can get it to do is alert an “undefined” response.
How can I write the function to have it find things like described above
Also one step further. How can i edit the data that is in the row that was found based on the search input? (I have not written that function yet)
html
<!--jquery-2.1.4.js-->
<body>
<input type="text" id="dataGoesHere" />
<input type="text" id="moredataGoesHere" />
<input type="text" id="mostdataGoesHere" />
<button id="clickme">Save</button>
<div id="saved"></div>
<br><br>
<input type="text" id="searchString" />
<button id="search">search</button>
</body>
js
$(document).ready(function() {
myDb = function () {
var name = "test",
version = "1",
db,
testStoreName = "exampleStore",
testIndexName = "testIndexName",
addToTestIndex = false,
init = function () {
var deferred = $.Deferred(),
openRequest = indexedDB.open(name, version);
openRequest.onupgradeneeded = dbUpgrade;
openRequest.onsuccess = dbOpen;
openRequest.onerror = dbError;
return deferred.promise();
function dbUpgrade(evt) {
//here our db is at evt.target.result here we can adjust stores and indexes
var thisDb = evt.target.result, //the current db we are working with
newStore = thisDb.createObjectStore(testStoreName, {keyPath: "id", autoIncrement: true});
//Using indexes, you can target specific keys, this can be an array!
newStore.createIndex("testIndexKey", "testIndexKey", {unique : false});
console.log("Doing an upgrade");
}
function dbOpen(evt) {
console.log("DB successfully opened");
db = evt.target.result;
deferred.resolve();
getAllItems (function (items) {
var len = items.length;
for (var i = 0; i < len; i += 1) {
console.log(items[i]);
$('#saved').append('<p>'+items[i].item + ' ' + items[i].george + ' ' + items[i].column3 + ' ' + items[i].id + '</p>');
}
});
}
function dbError(error) {
console.log("DB Error");
console.log(error);
deferred.reject(error);
}
},
add = function(item, bob, villa) {
var itemToAdd = {"item" : item, "george" : bob, "column3" : villa},
objStore,
request,
deferred = $.Deferred();
if (!addToTestIndex) {
//here we will add half the entries to the index
//See http://stackoverflow.com/questions/16501459/javascript-searching-indexeddb-using-multiple-indexes for a better example
addToTestIndex = !addToTestIndex;
itemToAdd.testIndexKey = "This is a test";
}
//first get the object store with the desired access
objStore = db.transaction([testStoreName], "readwrite").objectStore(testStoreName);
//next create the request to add it
request = objStore.add(itemToAdd);
request.onsuccess = function (evt) {
deferred.resolve(evt.target.result);
};
request.onerror = function (evt) {
deferred.reject(evt);
};
return deferred.promise();
},
get = function (index) {
//Since our store uses an int as a primary key, that is what we are getting
//The cool part is when you start using indexes...
var deferred = $.Deferred(),
store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
request = store.get(parseInt(index));
request.onsuccess = function (evt) {
console.log(evt);
deferred.resolve(evt.target.result);
};
request.onerror = function (evt) {
deferred.reject("DBError: could not get " + index + " from " + testStoreName);
};
return deferred.promise();
},
getAllItems = function(callback) {
var trans = db.transaction(testStoreName, IDBTransaction.READ_ONLY);
var store = trans.objectStore(testStoreName);
var items = [];
trans.oncomplete = function(evt) {
callback(items);
};
var cursorRequest = store.openCursor();
cursorRequest.onerror = function(error) {
console.log(error);
};
cursorRequest.onsuccess = function(evt) {
var cursor = evt.target.result;
if (cursor) {
items.push(cursor.value);
cursor.continue();
}
};
},
searchItems = function(searchString) {
var deferred = $.Deferred(),
store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
request = store.get(searchString);
request.onerror = function(event) {
// Handle errors!
alert("error");
};
request.onsuccess = function(event) {
alert('start seach')
// Do something with the request.result!)
alert(event.target.result);
alert('end search')
};
};
return {
init: init,
get: get,
add: add,
getAllItems: getAllItems,
searchItems: searchItems
};
}
var db = new myDb();
db.init().then(function () {
$("#clickme").click(function(evt) {
//add, then we will get the added item from the db
console.log("Adding new item to db");
db.add($('#dataGoesHere').val(), $('#moredataGoesHere').val(), $('#mostdataGoesHere').val())
.then(function (res) {
return db.get(res);
})
.then(function (res) {
$('#saved').append('<p>'+res.item+' '+res.george+' '+res.column3+'</p>');
});
});
$("#search").click(function(evt) {
// search for a specific row
console.log("searching");
db.searchItems($('#searchString').val());
});
})
});
First thing (and could be the probable cause): Are you having an index on the key you are trying to search? In you case, for data as name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ if you trying to search for "Andrew", then you should be having an index created on "name". If it is not there then you will not be able to make a search and that's what probably could be happening.
Next: In the data store there could be more than one rows with name as Andrew, so you can have a cursor open using the index and then loop through all value and get the desired one. Something like (I am just throwing you an idea through this code snippet):
var objectStoreHandler = transaction.objectStore(selectDataObj.tblName);
var indexHandler = objectStoreHandler.index(selectDataObj.whereColObj.whereColNameArr[0]);
var cursorHandler = indexHandler.openCursor(keyRange);
cursorHandler.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
console.log("!!!!!");
if (cursor.value != null && cursor.value != undefined) {
resultArr.push(cursor.value);
}
cursor["continue"]();
} else {
console.log("################### " + resultArr);
return successCallBack(resultArr);
}
return;
};
i've got an error, and only on android:
i have a code like this:
var selfWin;
var blackScreen;
var actInd;
var Login = require('ui/common/Login');
var myLogin;
var HomeView = require('ui/common/Home');
var homeView;
function ApplicationWindow() {
var selfWin = Ti.UI.createWindow({
backgroundColor:'#ffffff',
navBarHidden:true,
exitOnClose:true
});
blackScreen = Ti.UI.createLabel({
backgroundColor:'#000000',
opacity:0.40,
top:0,
height:'100%',
width:'100%',
zIndex:100
});
actInd = Ti.UI.createActivityIndicator({
width:50,
height:50,
zIndex:101
});
selfWin.add(blackScreen);
selfWin.add(actInd);
Ti.App.HideBlackScreen();
Ti.App.GoToFirstView();
return selfWin;
}
Ti.App.ShowBlackScreen = function ShowBlackScreen() {
blackScreen.show();
actInd.show();
};
Ti.App.HideBlackScreen = function HideBlackScreen() {
blackScreen.hide();
actInd.hide();
};
Ti.App.GoToFirstView = function GoToFirstView() {
myLogin = new Login();
selfWin.add(myLogin);
if (homeView) {
selfWin.remove(homeView);
}
};
Ti.App.GoToHome = function GoToHome() {
homeView = new HomeView();
selfWin.add(homeView);
selfWin.remove(myLogin);
};
//make constructor function the public component interface
module.exports = ApplicationWindow;
and this error occoured at selfWin.add(myLogin); inside the GoToFirstView() function, and only on android.
someone can help me?
Thanks a lot
try to make your selfWin object global like below.Because it is private variable which is not exist out side that Application function(). There are two way to achieve this.
1.
var selfWin;
function ApplicationWindow() {
selfWin = Ti.UI.createWindow({
backgroundColor : '#ffffff',
navBarHidden : true,
exitOnClose : true
});
}
2.Pass your window object with your function like below.
Ti.App.GoToFirstView(selfWin);
Ti.App.GoToFirstView = function GoToFirstView(selfWin) {
myLogin = new Login();
selfWin.add(myLogin);
if (homeView) {
selfWin.remove(homeView);
}
};
Best Regards,
Nitin Chavda