Please find the below code...
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
</head>
<body>
<div data-role="page">
<div data-role="header">
<h2>Header</h2>
</div>
<div data-role="content">
<ul data-role="listview" data-inset="true">
<li>
<p class="question"></p>
<div class="answerTxt"></div>
</li>
</ul>
</div>
<div data-role="footer" data-position="fixed">
<h3>Footer</h3>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script>
var ct = 0;
var jsonObj = {
"questions": [
"question 1",
"question 2",
"question 3"
],
"Type": [
"radio",
"checkbox",
"radio"
],
"Value": [
["Yes","No","Not Applicable"],
["Land","Garden","House","Office"],
["Good","Fair","Poor"]
]
}
$(document).on('pagebeforeshow',"[data-role=page]", function() {
init();
});
$(document).on("swipeleft","[data-role=page]",function(event) {
ct++;
init();
});
$(document).on("swiperight","[data-role=page]",function(event) {
ct--;
init();
});
function init() {
$(".answerTxt").empty();
$(".question").text((ct+1)+". "+jsonObj.questions[ct]);
if (jsonObj.Type[ct] == "radio" || jsonObj.Type[ct] == "checkbox"){
$(".answerTxt").append('<fieldset data-role="controlgroup" id="compCon"/>');
for(var i=0; i<jsonObj.Value[ct].length; i++){
$("#compCon").append('<label for="'+i+'"id="'+i+'">'+jsonObj.Value[ct][i]+'</label><input type="'+jsonObj.Type[ct]+'" name="rg2" id="'+i+'"/>');
$(".answerTxt").trigger("create");
$("input[type='"+jsonObj.Type[ct]+"']:first").attr("checked",true).checkboxradio("refresh");
}
}
}
</script>
</body>
</html>
In this example i am using swipe event to change the question. It works fine...
My question is how i move the content div in the swipe direction, and load the same div with new question and data..
for example please find the following link ... http://jquerymobile.com/demos/1.3.0-beta.1/docs/demos/swipe/swipe-page.html#
NOTE:
above example shows loading a new page in each swipe. Here what i want is how i load the new div with new data?
Thanks in advance...
if you look at the source code of the demo you mention youll see it shows
$( document ).on( "swiperight", page, function() {
$.mobile.changePage( prev + ".html", { reverse: true } );
});
you will just need to use the swiperight and swipeleft events to do what you need
Related
I am trying to call ajax from android webview and it's not working. I am getting this error in console window
08-29 12:28:16.411: E/CONTENT(14146): [object Object] # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
08-29 12:28:16.536: E/CONTENT(14146): Uncaught TypeError: undefined is not a function # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
08-29 12:28:16.683: E/CONTENT(14146): Uncaught TypeError: undefined is not a function # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
08-29 12:28:16.883: E/CONTENT(14146): Uncaught TypeError: undefined is not a function # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
08-29 12:28:17.202: E/CONTENT(14146): Uncaught TypeError: undefined is not a function # 1: http://loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
I am using this android code
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
return super.shouldOverrideUrlLoading(view, url);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
if(url.equals("http://xyz")){
editor.putString("login", "true");
editor.commit();
trytologin = false;
}else if(url.equals("http://xyz")){
editor.clear();
editor.commit();
Intent intent = new Intent(WebActivity.this,MainActivity.class);
if(trytologin == true){
intent.putExtra("login", "failed");
}
startActivity(intent);
finish();
}
if(!isNetworkAvailable()){
alertDialog();
linearLayout.setVisibility(View.VISIBLE);
webview.setVisibility(View.GONE);
}else{
webview.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
}
dialog.dismiss();
//pd.dismiss();
//Toast.makeText(WebActivity.this, url, Toast.LENGTH_LONG).show();
}
});
webview.setWebChromeClient(new WebChromeClient(){
#Override
public boolean onConsoleMessage(ConsoleMessage cm)
{
Log.e("CONTENT", String.format("%s # %d: %s",
cm.message(), cm.lineNumber(), cm.sourceId()));
return true;
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setDatabaseEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setAllowFileAccessFromFileURLs(true);
webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setAllowContentAccess(true);
webview.getSettings().setUseWideViewPort(true);
I am trying to call this ajax file
function GoogleFetchAndFillHistoryLocation(t,e,n,o){$.ajax({url:"http://maps.googleapis.com/maps/api/geocode/json?latlng="+t+","+e,success:function(t){var e=[],c="",r="";t.results[0].address_components.forEach(function(t,n,o){"Unnamed Road"!=t.long_name&&e.push(t.long_name),t.types.includes("sublocality")&&(c=t.long_name),t.types.includes("locality")&&(r=t.long_name)}),console.log(t.results[0].formatted_address);var i=e.join(", "),a=c+", "+r;o.html(i),n.html(a)},error:function(t){o.html("Some error occurred while fetching address")}})}function HistorySelector(t){this.$selector=t}!function(t){"use strict";var e=function(t,n){var o=/[^\w\-\.:]/.test(t)?new Function(e.arg+",tmpl","var _e=tmpl.encode"+e.helper+",_s='"+t.replace(e.regexp,e.func)+"';return _s;"):e.cache[t]=e.cache[t]||e(e.load(t));return n?o(n,e):function(t){return o(t,e)}};e.cache={},e.load=function(t){return document.getElementById(t).innerHTML},e.regexp=/([\s'\\])(?!(?:[^{]|\{(?!%))*%\})|(?:\{%(=|#)([\s\S]+?)%\})|(\{%)|(%\})/g,e.func=function(t,e,n,o,c,r){return e?{"\n":"\\n","\r":"\\r"," ":"\\t"," ":" "}[e]||"\\"+e:n?"="===n?"'+_e("+o+")+'":"'+("+o+"==null?'':"+o+")+'":c?"';":r?"_s+='":void 0},e.encReg=/[<>&"'\x00]/g,e.encMap={"<":"<",">":">","&":"&",'"':""","'":"'"},e.encode=function(t){return(null==t?"":""+t).replace(e.encReg,function(t){return e.encMap[t]||""})},e.arg="o",e.helper=",print=function(s,e){_s+=e?(s==null?'':s):_e(s);},include=function(s,d){_s+=tmpl(s,d);}","function"==typeof define&&define.amd?define(function(){return e}):t.tmpl=e}(this),HistorySelector.prototype.bindEvents=function(){var t=this;this.$selector.on("change",function(){t.fetchData()})},HistorySelector.prototype.fetchData=function(){$.ajax({context:this,url:this.$selector.data("url"),data:{profiles:{interval:this.$selector.val()}},headers:{"X-Auth-Token":$("#auth-token").data("token")},success:function(t){console.log(t),this.populateData(t),$(".location-panel").each(function(t,e){var n=$(e);setTimeout(function(){GoogleFetchAndFillHistoryLocation(n.data("lat"),n.data("long"),n.find(".short-location"),n.find(".formatted-address"))},200*t)})},error:function(t){console.log(t)}})},HistorySelector.prototype.populateData=function(t){var e=$(tmpl("history-locations",t).trim());$(".history-locations").empty().append(e),$("body").scrollTop()<180&&$("html, body").animate({scrollTop:"180vh"},"slow")},HistorySelector.prototype.init=function(){},$(function(){$(".selectors input").each(function(){var t=new HistorySelector($(this));t.init(),t.bindEvents()})});
you can see the ajax file on this link as well - http://www.loconav.com/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js
I am using this html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Babatrucks</title>
<meta content="authenticity_token" name="csrf-param" />
<meta content="lNJn5/GLbnS0cgUYjalFUT+UsgCcDckhWHcqI32OeJ0=" name="csrf-token" />
<link href="/assets/application-33b3164661d3b2d630f9cbc88419feb4.css" media="all" rel="stylesheet" />
<link href="/assets/m_application-9613cb73f45d486ef514a74fa1964a46.css" media="all" rel="stylesheet" />
<script src="/assets/application-95d8b0297f927b393dd0e1aaf163bc4d.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<link href="/assets/m/trucks/show-bcd1a590d01e03df2a78b4c5dbd1a975.css" media="screen" rel="stylesheet" />
<script src="/assets/m/history_selector-1b620f001e31e9dfeff6981b3ee9b290.js"></script>
<div class="row top-bar">
<div class="col-xs-2 text-center">
<a class="back-arrow" href="/m/trucks">
<i class="fa fa-chevron-left" aria-hidden="true"></i>
</a> </div>
<div class="col-xs-8 text-center title">
NL 01L 2273
</div>
<div class="col-xs-2 text-right">
</div>
</div>
<div class="row">
<iframe class='locate-map' src="/m/trucks/296/locate"></iframe>
<div class="col-xs-12">
<div class="row">
<div class="selectors rohan-container">
<ul class="backline">
<hr class="rohan-hr">
<li>
<label for="profiles_interval_1">1 hours</label>
<!-- <input type="radio" id="f-option" name="selector"> -->
<input data-url="http://www.example.com/" id="profiles_interval_1" name="profiles[interval]" type="radio" value="1" />
<div class="check"></div>
</li>
<li>
<label for="profiles_interval_6">6 hours</label>
<!-- <input type="radio" id="s-option" name="selector"> -->
<input data-url="http://www.example.com/" id="profiles_interval_6" name="profiles[interval]" type="radio" value="6" />
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<label for="profiles_interval_24">24 hours</label>
<!-- <input type="radio" id="t-option" name="selector"> -->
<input data-url="http://www.example.com/" id="profiles_interval_24" name="profiles[interval]" type="radio" value="24" />
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
<!-- rohan ends -->
</div>
<div class="row history">
<div class="col-xs-12">
<div class="row">
<div class="history-locations col-xs-12"></div>
</div>
</div>
</div>
</div>
</div>
<div class="hidden" id="auth-token" data-token=""></div>
<script src="/assets/timeline/modernizr-04ac4151e53119ba85cdc7679379cd0d.js"></script>
<script type="text/x-tmpl" id="history-locations">
<section id="cd-timeline" class="cd-container">
{% for (var i = 0; i < o['profiles'].length; i++) { %}
<div class="cd-timeline-block location-panel" data-lat="{%= o['profiles'][i]['lat'] %}" data-long="{%= o['profiles'][i]['long'] %}">
<div class="cd-timeline-img cd-picture">
<img alt="Picture" src="/assets/timeline/cd-icon-location-20955b176b47169a313e3c8c11803cc1.svg" />
</div> <!-- cd-timeline-img -->
<div class="cd-timeline-content">
<h2 class="">{%= o['profiles'][i]['actual_received_at'] %}</h2>
<p class="formatted-address"></p>
</div> <!-- cd-timeline-content -->
</div> <!-- cd-timeline-block -->
{% } %}
</section>
</script>
<script src="/assets/timeline/main-f1dcfd5d7be80e6258f34c7dded2ee86.js"></script>
<script type="text/javascript">
function FetchAndFillLocation(lat, long, infoDiv, truckNumber, speed) {
var request = new XMLHttpRequest();
var method = 'GET';
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='
+ lat
+ ','
+ long
+ '&sensor=true';
var async = true;
request.open(method, url, async);
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
var data = JSON.parse(request.responseText);
var address = data.results[0];
infoDiv.empty();
infoDiv.append('<div class="info-box-title"><span class="left-align-number"><i class="fa fa-truck"></i> '+ truckNumber +'</span><span class="right-align-speed"><i class="fa fa-tachometer"></i> ' + speed + ' Km/h</span></div><div class="info-box-text">' + address.formatted_address + '</div>');
}
};
request.send();
}
function UpdateMarkerPosition(current_location_div) {
var request = new XMLHttpRequest();
var method = 'GET';
var url = '/api/v1/trucks/location?truck[slug]=abc';
var async = true;
request.open(method, url, async);
request.setRequestHeader('X-Auth-Token', 'abc');
request.onreadystatechange = function(){
if(request.readyState == 4){
if(request.status == 200) {
var data = JSON.parse(request.responseText).current_cordinate;
var truckCords = { lat: data.lat, lng: data.long }
FetchAndFillLocation(truckCords.lat, truckCords.lng, current_location_div, data.key, data.speed);
}
setTimeout(function() {
UpdateMarkerPosition(current_location_div)
}, 10000);
}
};
request.send();
}
$(function() {
UpdateMarkerPosition($('.current-location'));
})
</script>
</div>
</div><!--/row-->
<footer>
</footer>
</div> <!-- /container -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-81486803-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
I assume, that a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with (jQuery) and you need to have (jQuery);.
Consider adding jquery locally or via a CDN.
I have this weird error in a Cordova/AngularJS app.
Sometimes (rarely) AngularJS cannot find the controller and chrashes, leaving users with a half-loaded unresponsive view.
The error only seems to happen when the phone has been locked for some time and is next to impossible for me to recreate at a regular basis. It just happens sometimes.
When the user close the app and restart it everything works fine again.
Thus far I have only received complaints about this error for Android devices and not for iOS devices.
EDIT: I have also now seen the error on iOS devices.
I really hope someone is able to shed light on this issue.
My index.html looks like this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="guideApp">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; script-src * 'self' 'unsafe-eval' 'unsafe-inline' https://api.tiles.mapbox.com/mapbox.js/v2.1.6/mapbox.js http://connect.facebook.net/en_GB/sdk.js;">
<link rel="stylesheet" href="css/snap.css" />
<link rel='stylesheet' href='css/mapbox.css' />
<link rel="stylesheet" href="css/leaflet.css" />
<link rel="stylesheet" href="css/guideapp.css" />
<link rel="stylesheet" href="css/xpengineicons.css" />
<!--<link rel="stylesheet" href="css/guideappTest.css" />-->
<title></title>
<link rel="icon" type="image/png" href="img/favicon.png"/>
<meta name="application-name" content="GuideApp"/>
<meta name="msapplication-TileColor" content="#000000" />
<meta name="msapplication-TileImage" content="img/favicons/mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="img/favicons/mstile-70x70.png" />
<meta name="msapplication-square150x150logo" content="img/favicons/mstile-150x150.png" />
<meta name="msapplication-wide310x150logo" content="img/favicons/mstile-310x150.png" />
<meta name="msapplication-square310x310logo" content="img/favicons/mstile-310x310.png" />
</head>
<body ng-controller="globalCtrl" data-snap-ignore="true">
<div class="snap-drawers">
<div class="snap-drawer snap-drawer-left sideMenu">
{{::langPack.startPage[lang]}}
{{::langPack.selectTour[lang]}}
{{::langPack.map[lang]}}
{{::langPack.news[lang]}}
{{::langPack.photoMenu[lang]}}<i class="icon-angle-down fotoToggleAngle"></i>
<div class="fotoMenu" id="fotoMenu">
{{::langPack.followAnothersTour[lang]}}
{{::langPack.endPhototour[lang]}}
{{::langPack.seePreviousTour[lang]}}
<!--{{::langPack.photoFromGallery[lang]}}-->
{{::langPack.selectFromGallery[lang]}}
<!--[Smaller radius]-->
<!--[Larger radius]-->
<!--[{{langPack.toggleActionRadius[lang]}}]-->
<!--[End waypoint tour] -->
</div>
{{::langPack.about[lang]}}
<a href="#" ng-click="sync.checkUpdates();">
{{::langPack.sync[lang]}}
<span id="updateCheck" class="updateCheck"><div class="circle"></div>{{::langPack.checkForUpdates[lang]}}</span>
<span id="uptodate" class="updateCheck uptodate"><i class="icon-ok"></i>{{::langPack.upToDate[lang]}}</span>
</a>
{{::langPack.showIntroOverlay[lang]}}
</div>
</div>
<div id="content" class="snap-content content" ng-style="customBg">
<nav id="header" ng-controller="cameraCtrl">
<img src="img/menu-regular.svg"><!--<div class="menuNotification" ng-if="photosInUploadQue > 0">{{photosInUploadQue}}</div>-->
<i class="icon-angle-up"></i>
<h1></h1>
<img ng-src="{{customLogo}}" id="logo">
<!-- Kamera når det virker -->
<i class="icon-camera"></i>
<!-- <i class="icon-angle-down"></i> -->
<!-- <i class="icon-angle-up"></i> -->
<!-- <a onclick = "window.open('http://guideapp.tmts.dk/', '_blank', 'location=yes'); return false;" id="viewInBrowser" class="uploadBtn"><i class="icon-angle-down"></i></a> -->
<div id="uploadPopupOverlay" class="popupOverlay" ng-click="closeUploadPopup();"></div>
<section id="uploadPopup">
<p>{{::langPack.uploadAndShare[lang]}}</p>
<form novalidate ng-submit="uploadPhotosSubmittedByPopup($event)">
<label for="emailInput" ng-show="showEmail === true">
{{::langPack.yourEmail[lang]}}
<div class="error" ng-if="emailMsg">{{::emailMsg}}</div>
</label>
<input type="email" value="{{emailAdress}}" required name="emailInput" ng-model="emailAdress" ng-show="showEmail === true" id="emailAdress">
<label for="titleInput">
{{::langPack.yourTitel[lang]}}
<div class="error" ng-if="titleMsg">{{::titleMsg}}</div>
</label>
<input type="text" value="{{tourTitle}}" name="titleInput" ng-model="tourTitle" id="uploadTitle" required>
<p class="emailExists" ng-show="showEmail === false"><span compile="langPack.sendTo[lang]"></span> [{{::langPack.editEmail[lang]}}]</p>
<button class="btn left" ng-click="closeUploadPopup();">{{::langPack.cancel[lang]}}</button>
<button type="submit" class="btn right">{{::langPack.ok[lang]}}</button>
</form>
</section>
</nav>
<div class="slideInLeft" ng-view></div>
</div>
<aside ng-class="{active: showIntro}" id="intro" ng-swipe-left="nextSlide()" class="" ng-swipe-right="prevSlide()">
<div>
<div id="introSwipe">
<section id="intro{{$index+1}}" class="introSlide" ng-class="{'active': $index === 0}" ng-repeat="slide in introSlides" style="background-image: url('{{slide}}')"></section>
</div>
<section id="noShow">
<div class="slideNavigation">
<button ng-click="prevSlide()" ng-class="{disabled: firstSlide}">{{::langPack.prevSlide[lang]}}</button>
<div class="slideProgress">{{slideProgress}}/{{introSlides.length}}</div>
<button ng-click="nextSlide()" ng-class="{disabled: lastSlide}">{{::langPack.nextSlide[lang]}}</button>
</div>
</section>
</div>
<a id="closeIntro" href="#" ng-click="toggleIntro(); $event.preventDefault()">{{::langPack.toggleIntroText[lang]}}</a>
</aside>
<section id="confirmOverlay" class="popupOverlay" ng-click="confirmValue = false;">
<section class="checkPopup confirmPopup" id="confirmPopup">
<p id="confirmMessage"></p>
<button class="btn right" ng-click="confirmValue = true;">{{::langPack.ok[lang]}}</button>
<button class="btn left" ng-click="confirmValue = false;">{{::langPack.cancel[lang]}}</button>
</section>
</section>
<section id="spinnerOverlay" class="popupOverlay">
<section class="checkPopup spinnerPopup" id="spinnerPopup">
<div class="circle"></div>
<div class="spinnerText" id="spinnerText"></div>
</section>
</section>
<section id="statusOverlay" class="popupOverlay" ng-click="status.hide()">
<section class="checkPopup statusPopup" id="statusPopup">
<p id="statusText"></p>
<button class="btn" ng-click="status.hide()">Ok</button>
</section>
</section>
<!-- JavaScript libraries -->
<script src="cordova.js"></script>
<script src="js/libs/angular.min.js"></script>
<script src="js/libs/angular-locale_da-dk.js"></script>
<script src="js/libs/angular-route.min.js"></script>
<script src="js/libs/angular-animate.min.js"></script>
<script src="js/libs/angular-touch.min.js"></script>
<script src="js/libs/snap.min.js"></script>
<script src="js/libs/md5.js"></script>
<script src="js/libs/angular-listview.min.js"></script>
<!-- Mapbox -->
<!--<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.6/mapbox.js'></script>-->
<!-- <script src='https://api.mapbox.com/mapbox.js/plugins/leaflet-omnivore/v0.2.0/leaflet-omnivore.min.js'></script> Draw GPX 20151014 -->
<!-- leaflet -->
<script src="js/libs/leaflet.js"></script>
<script src='js/libs/leaflet-omnivore.min.js'></script> <!-- Draw GPX 20151014 -->
<script src='js/libs/leaflet-tilelayer-cordova.js'></script> <!-- Offline maps -->
<!-- Custom script files -->
<script src="js/app.js"></script>
<script src="js/index.js"></script>
<!-- included controllers -->
<script src="controllers/globalCtrl.js"></script>
<script src="controllers/homeCtrl.js"></script>
<script src="controllers/aboutCtrl.js"></script>
<script src="controllers/tourSelectCtrl.js"></script>
<script src="controllers/mapCtrl.js"></script>
<script src="controllers/cameraCtrl.js"></script>
<script src="controllers/viewtoursCtrl.js"></script>
<script src="controllers/commonToursCtrl.js"></script>
<script src="controllers/highscoreCtrl.js"></script>
<script src="controllers/downloadCtrl.js"></script>
<script src="controllers/waypointCtrl.js"></script>
<script src="controllers/waypointGalleryCtrl.js"></script>
<script src="controllers/endCtrl.js"></script>
<script src="controllers/newsCtrl.js"></script>
</body>
</html>
AngularJS is loaded with app.js:
// Init angular.js
var guideApp = angular.module('guideApp', ['ngRoute', 'ngAnimate', 'ngTouch']);
guideApp.config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {
$routeProvider.when('/', {
controller: 'homeCtrl',
templateUrl: 'views/home.html'
}).when('/home', {
controller: 'homeCtrl',
templateUrl: 'views/home.html'
}).when('/tourSelect', {
controller: 'tourSelectCtrl',
templateUrl: 'views/tourSelect.html'
}).when('/map', {
controller: 'mapCtrl',
templateUrl: 'views/map.html'
}).when('/about', {
controller: 'aboutCtrl',
templateUrl: 'views/about.html'
}).when('/viewtours', {
controller: 'viewtoursCtrl',
templateUrl: 'views/viewtours.html'
}).when('/commonTours', {
controller: 'commonToursCtrl',
templateUrl: 'views/commonTours.html'
}).when('/highscore', {
controller: 'highscoreCtrl',
templateUrl: 'views/highscore.html'
}).when('/download', {
controller: 'downloadCtrl',
templateUrl: 'views/download.html'
}).when('/waypoint', {
controller: 'waypointCtrl',
templateUrl: 'views/waypoint.html'
}).when('/waypointGallery', {
controller: 'waypointGalleryCtrl',
templateUrl: 'views/waypointGallery.html'
}).when('/end', {
controller: 'endCtrl',
templateUrl: 'views/end.html'
}).when('/news', {
controller: 'newsCtrl',
templateUrl: 'views/news.html'
}).otherwise({
redirectTo: '/'
});
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|cdvfile|file):/);
}]);
guideApp.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
}])
// custom on touchstart directive
/*guideApp.directive('guideappTouchstart', [function () {
return function(scope, element, attr) {
element.on('touchstart', function (event) {
scope.$apply(function () {
scope.$eval(attr.guideappTouchstart);
});
});
};
}]);*/
The index.js file looks like this:
var http,
app = {
initialize: function () {
this.bindEvents();
},
bindEvents: function () {
if (!window.cordova) {
this.onDeviceReady();
} else {
document.addEventListener('deviceready', this.onDeviceReady, false);
}
},
onDeviceReady: function () {
app.receivedEvent('deviceready');
console.log('Device ready');
if (window.cordova) {
// find and set the filesystem root
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(1, 0, function (fileSystem) {
console.log("got filesystem: "+fileSystem.name); // displays "persistent"
//console.log(fileSystem.root.fullPath); // displays "/"
window.rootFS = fileSystem.root;
});
}
},
receivedEvent: function (id) {
//angularInit();
this.platform();
},
server: function (wwwroot) {
if (httpd) {
httpd.getURL(function (url) {
if(url.length > 0) {
document.getElementById('url').innerHTML = "server is up: <a href='" + url + "' target='_blank'>" + url + "</a>";
} else {
httpd.startServer({
'www_root' : wwwroot,
'port' : 8080
}, function (url) {
//updateStatus();
}, function (error) {
console.log('server error ', error);
});
}
}, function () {});
} else {
console.log('CorHttpd plugin not available/ready');
}
},
platform: function () {
var deviceType;
if (navigator.userAgent.match(/Android/i)) { // Android
if (navigator.userAgent.match(/Mobile/i)) { // Android smartphone
console.log('Android smartphone');
deviceType = 'mobile';
} else { // Android tablets
//console.log('Android tablet');
deviceType = 'tablet';
}
} else if (navigator.userAgent.match(/iPad/i)) { // IOS ipad
//console.log('IOS tablet');
deviceType = 'tablet';
} else if (navigator.userAgent.match(/iPhone/i)) { //IOS smartphone
//console.log('IOS smartphone');
deviceType = 'mobile';
} else { // Dekstop as default
//console.log('desktop');
deviceType = 'tablet';
}
}
};
app.initialize();
Here is the code
App.js
(...)
.state('app.dishdetails', {
url: '/menu/:id',
views: {
'mainContent': {
templateUrl: 'templates/dishdetail.html',
controller: 'DishDetailController'
}
}
});
Controller.js
.controller('DishDetailController', ['$scope', '$stateParams', 'menuFactory', 'favoriteFactory', 'baseURL','$ionicPopover', '$ionicListDelegate', '$ionicModal', function($scope, $stateParams, menuFactory, favoriteFactory, baseURL, $ionicPopover, $ionicListDelegate, $ionicModal) {
$scope.addFavoriteMenu = function(index){
console.log("index is " + index);
};
// .fromTemplateUrl() method
$ionicPopover.fromTemplateUrl('templates/dish-detail-popover.html', {
scope: $scope
}).then(function(popover) {
$scope.popover = popover;
});
$scope.openPopover = function($event) {
$scope.popover.show($event);
};
$scope.closePopover = function() {
$scope.popover.hide();
};
//Cleanup the popover when we're done with it!
$scope.$on('$destroy', function() {
$scope.popover.remove();
});
// Execute action on hide popover
$scope.$on('popover.hidden', function() {
// Execute action
});
// Execute action on remove popover
$scope.$on('popover.removed', function() {
// Execute action
});
}])
Main HTML
<ion-view view-title="Dish Details">
<ion-nav-buttons side="secondary">
<div class="buttons">
<button class="button button-icon icon ion-more"
ng-click="openPopover($event)"></button>
</div>
</ion-nav-buttons>
<ion-content>
(...)
</ion-content>
</ion-view>
Popover HTML
<ion-popover-view>
<ion-content>
<ul class="list">
<li class="item" ng-click="addFavoriteMenu({{dish.id}})">
Add to Favorites
</li>
</ul>
</ion-content>
db.json
"dishes": [
{"id": 0};
{"id": 1};
{"id": 2};
]
I can't get the parameter in the "addFavoriteMenu({{dish.id}})" in the controller.js, it always come out as undefined
but, when I try to inspect using Google Chrome, the ID could display properly in [ion-popover-view]
Is there any mistake that I create on here? or anything?
Trying to reproduce your issue I noticed that your JSON is wrong: there are semicolons (;) at the end of each line instead of colons (,).
Howevere here is a working snippet:
angular.module('ionicApp', ['ionic'])
.controller('AppCtrl', function($scope, $ionicPopover) {
$scope.dishes = [
{"id": 0},
{"id": 1},
{"id": 2}
];
$scope.addFavoriteMenu = function(index) {
console.log(index);
alert("index is "+index);
}
$ionicPopover.fromTemplateUrl('templates/popover.html', {
scope: $scope,
}).then(function(popover) {
$scope.popover = popover;
});
});
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic Popover</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body class="platform-ios" ng-controller="AppCtrl">
<div class="bar bar-header bar-positive">
<h1 class="title">Popover</h1>
<div class="buttons">
<button class="button button-icon ion-more" ng-click="popover.show($event)">
</button>
</div>
</div>
<ion-content class="padding has-header">
Click the more info icon in the top right. In an actual app the platform style will automatically be set.
</ion-content>
<script id="templates/popover.html" type="text/ng-template">
<ion-popover-view>
<ion-content>
<ul class="list">
<li ng-repeat="dish in dishes" class="item" ng-click="addFavoriteMenu({{dish.id}})">
Add to Favorites {{dish.id}}
</li>
</ul>
</ion-content>
</ion-popover-view>
</script>
</body>
</html>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
<!DOCTYPE html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css">
</head>
<body>
<div data-role="page" id="twitterPage" data-theme="a">
<div data-role="content">
<ul id="tweet-list" data-role="listview" data-inset="true" data-filter="true" >
</ul>
</div>
</div>
<script type="text/javascript">
$.ajax({
url: "http://192.168.1.60/json_android/getItemData.php",
jsonpCallback: 'item',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
var markup = "";
$.each(data.list, function(i, elem) {
var $template = $('<li> <div class=ui-grid-a> <div class=ui-block-a> </div> <div class=ui-block-b> </div> </div> </li>');
$template.find(".ui-block-a").append('<a href=# id=' + elem['itemId'] + '>' + elem['itemId'] + '</a>');
$template.find(".ui-block-b").append("<input type=text />")
markup += $template.html();
});
$("#tweet-list").append(markup).listview("refresh", true);
// Transition to the Twitter results page.
//$.mobile.changePage($("#twitterPage"));
},
error: function(request, error) {
alert(error);
}
});
$('#tweet-list').on('click', 'a', function(event) {
event.preventDefault();
console.log($(this).closest('div').next('.ui-block-b').find('input').val());
});
</script>
</body>
I tried the above code to populate a list view with data. It is working thanks to stackoverflow, but when I try it on an Android tablet it is not working. It only displays the search bar of the list view.
Try this add your script inside $(document).on('pageshow',function(){});
<!DOCTYPE html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css">
</head>
<body>
<div data-role="page" id="twitterPage" data-theme="a">
<script type="text/javascript">
$(document).on('pageshow',function(){
$.ajax({
url: "http://192.168.1.60/json_android/getItemData.php",
jsonpCallback: 'item',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
var markup = "";
$.each(data.list, function(i, elem) {
var $template = $('<li> <div class=ui-grid-a> <div class=ui-block-a> </div> <div class=ui-block-b> </div> </div> </li>');
$template.find(".ui-block-a").append('<a href=# id=' + elem['itemId'] + '>' + elem['itemId'] + '</a>');
$template.find(".ui-block-b").append("<input type=text />")
markup += $template.html();
});
$("#tweet-list").append(markup).listview("refresh", true);
// Transition to the Twitter results page.
//$.mobile.changePage($("#twitterPage"));
},
error: function(request, error) {
alert(error);
}
});
$('#tweet-list').on('click', 'a', function(event) {
event.preventDefault();
console.log($(this).closest('div').next('.ui-block-b').find('input').val());
});
});
</script>
<div data-role="content">
<ul id="tweet-list" data-role="listview" data-inset="true" data-filter="true" >
</ul>
</div>
</div>
</body>
Javascript does not work outside index.html page:
Project Test 1:
Index.html (with GEOLOCATION PAGE CODE) works fine
Project Test 2:
Index.html (with MENU PAGE CODE)
Geolocation.html (with GEOLOCATION PAGE CODE) javascript does not work
The page Geolocation.html opens up, but javascript does not run.
What am i missing?
GEOLOCATION PAGE CODE:
<!DOCTYPE html>
<html>
<head>
<!-- <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />-->
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" charset="utf-8" src="js/cordova-2.5.0.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Ready...';
navigator.geolocation.getCurrentPosition(onSuccess, onError, { maximumAge: 3000, timeout: 10000, enableHighAccuracy: false });
}
function onSuccess(position) {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Success...';
initialize(position.coords.latitude, position.coords.longitude);
}
function onError(error) {
var element = document.getElementById('geoTemp');
element.innerHTML = 'Error...';
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function initialize(latitude, longitude) {
var mapOptions = {
center: new google.maps.LatLng(latitude, longitude),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function onBodyLoad(){
alert("test!");
}
</script>
</head>
<body>
<h2>Location</h2>
<p id="geolocation">Finding geolocation...</p>
<p id="geoTemp"></p>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
MENU PAGE CODE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.3.0.css">
<link rel="shortcut icon" href="favicon.ico">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
<script type="text/javascript" src="js/cordova-2.5.0.js"></script>
</head>
<body>
<div data-role="page" id="pageMain">
<div data-role="header">
<h1>
TestPage
</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li><a href="geolocation.html" data-transition="slide">
<h2>Geolocation Test</h2>
<p>Testing</p>
</a></li>
</ul>
</div>
</div>
</body>
</html>
I have also tried to add an onload function to the body tag and call a test function but it didn't work either.
In the link to geolocation.html, add this attribute data-ajax="false". This will prevent jQuery from loading the page via Ajax.