Onsen - Cordova - AngularJs module is not available - android

I've an hybrid app for android, i'm using cordova and onsen + angular js.
This is my index.html file:
<html lang="en" ng-app="AppModel">
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<title>AppModel</title>
<!-- <link rel="stylesheet" href="css/plugins.css"/> -->
<link rel="stylesheet/less" href="css/plugins.less"/>
<link rel="stylesheet" href="lib/onsen/css/onsenui.css">
<link rel="stylesheet" href="lib/onsen/css/onsen-css-components.css">
<link rel="stylesheet/less" href="css/app.less"/>
<link rel="stylesheet/less" href="css/base-layout.less"/>
<script src="css/less.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<script src="js/lodash_3.2.0.min.js"></script>
<script src="lib/onsen/js/angular/angular.js"></script>
<script src="js/angular-google-maps_2.0.12.min.js"></script>
<script src="lib/onsen/js/angular/angular-touch.js"></script>
<script src="lib/onsen/js/onsenui.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/plugins.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="js/appStart.js"></script>
<script src="js/data/data.js"></script>
<script src="js/angularApp/controllers.js"></script>
<script src="js/angularApp/directives.js"></script>
<script src="js/angularApp/filters.js"></script>
</head>
<body >
<ons-sliding-menu
menu-page="modules/core/menu.html" main-page="modules/account_profile/login.html" side="left"
var="menu" type="reveal" max-slide-distance="260px" swipable="true" swipe-target-width="50">
</ons-sliding-menu>
</body>
</html>
This is the appStart.js
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
exitFunction : function(){
if (navigator.notification.confirm("Vuoi chiudere l'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
},
"AppModel",
["Ok","Annulla"]
));
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
ons.setDefaultDeviceBackButtonListener(function() {
if (navigator.notification.confirm("Vuoi chiudere l'app?",
function(index) {
if (index == 1) { // OK button
navigator.app.exitApp(); // Close the app
}
},
"AppModel",
["Ok","Annulla"]
));
});
/*
// Open any external link with InAppBrowser Plugin
$(document).on('click', 'a[href^=http], a[href^=https]', function(e){
e.preventDefault();
var $this = $(this);
var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), target);
});
*/
$(document).on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
//var target = $this.data('inAppBrowser') || '_blank';
window.open($this.attr('href'), "_system");
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
//var parentElement = document.getElementById(id);
//var listeningElement = parentElement.querySelector('.listening');
//var receivedElement = parentElement.querySelector('.received');
//listeningElement.setAttribute('style', 'display:none;');
//receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
(function() {
var app = angular.module('AppModel', ['onsen', 'angular-carousel', 'uiGmapgoogle-maps'])
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|mailto|tel|geo):/);
}
]);
document.addEventListener('deviceready', function() {
angular.bootstrap(document, ['AppModel']);
}, false);
})
And data.js, controller.js, filter.js, directive.js are all like this:
var app = angular.module('AppModel'); //this is the first line in each file
app.factory('MenuData', function(){ [...]
But when i launch the app in google chrome, the console says:
Uncaught Error: [$injector:nomod] Module 'AppModel' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.2.10/$injector/nomod?p0=AppModel
This message appears for the files data.js, controller.js, filter.js, directives.js due to the first line of each file.
I don't know what to do. Can someone help me?

Doesn't look like you're executing the line where the app module is created.
You must run the line
angular.module('appName', [dependencies]);
before you created your controllers and services, like the error message says.
Are you calling the anonymous function that creates the module? Just add an empty parenthesis and it should run:
(function() {
var app = angular.module(...
})();

As the error message says, you must specify the dependencies as the second argument. If none is needed, then pass an empty array.
change
var app = angular.module('AppModel'); //this is the first line in each file
to
var app = angular.module('AppModel', []); //this is the first line in each file
and run it again.
Additional information: https://docs.angularjs.org/api/ng/function/angular.module

Related

Connection and testing of SQLite with ionic framework

hello I am working on an android project i was trying to connect to a prepopulated SQLite database on my windows machine..but im unable to go about it.
I also want to know if i can test on windows machine or it is necessary to connect to a android device to test because im not able to see any output on the emulator.
Please help .Thanks
enter code here
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user- scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic DataBase</h1>
</ion-header-bar>
<ion-content ng-controller="ExampleController">
<button class="button" ng-click="SelectAll()">select</button>
<button class="button" ng-click="insert()">INSERT</button>
</ion-content>
</ion-pane>
</body>
</html>
enter code here
app.js
var example = angular.module('starter', ['ionic', 'ngCordova'])
var db = null;
example.run(function ($ionicPlatform,$cordovaSQLite) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
//window.Plugin.sqlDB.copy("newdata.db"), function ()
{
db = $cordovaSQLite.openDatabase("newdata.db");
//}, function (error) {
db = $cordovaSQLite.openDatabase("newdata.db");
}
});
});
example.controller("ExampleController", function ($scope, $cordovaSQLite) {
$scope.SelectAll = function() {
var query = "select ID, Dept from Department";
$cordovaSQLite.execute(db, query, []).then(function (res) {
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
}
}
console.log("selected-> " + res.rows.item(i).ID + " " + res.rows.item(i).Dept);
}, function (err) {
console.error("No result found");
});
}
});
example.controller("ExampleController", function($scope, $cordovaSQLite) {
$scope.insert = function (Dept) {
var query = "INSERT INTO Department (Dept) VALUES (Finance)";
$cordovaSQLite.execute(db, query, [Dept]).then(function (res) {
console.log("INSERT ID -> " + res.insertId);
}, function (err) {
console.error(err);
});
}
});
above is the code used in my project.
cordoba-sqlite-storage doesn't support using an existing database. You need: https://github.com/litehelpers/cordova-sqlite-ext
run the following in your project's folder:
ionic plugin remove cordova-sqlite-storage
ionic plugin add cordova-sqlite-ext

How to get User data (Public profile and Email ) In ionic framework

I am working on Ionic Mobile Application. After Creating Facebook Login button(Working fine) i want to get User data (Public profile and Email for my database.
My Index.html
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/angular-sanitize/angular-sanitize.min.js"></script>
<script src="js/ng-cordova.min.js"></script><script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
Controller.js
.controller('login',['$scope','myService','$location','$state','$timeout',function($scope,myService,$location,$state,$timeout)
{
$scope.fbLogin = function ($cordovaOauth,$http) {
facebookLogin(window.cordovaOauth, window.http);
console.log(fbLogin);
}
}])
app.js
var app = angular.module('starter', ['ionic', 'starter.controllers','starter.services','ngSanitize', 'ngCordova', 'ngCordovaOauth']);
Please tell me where i am doing wrong.
And Sometimes i Get $cordovaOauth error.
Modular is not Injected.
function login(){
facebookLogin(window.cordovaOauth, window.http);
}
function facebookLogin($cordovaOauth, $http)
{
$cordovaOauth.facebook("1633195863589792", ["email", "public_profile"], {redirect_uri: "http://localhost/callback"}).then(function(result){
displayData($http, result.access_token);
}, function(error){
alert("Error: " + error);
});
}
function displayData($http, access_token)
{
$http.get("https://graph.facebook.com/v2.2/me", {params: {access_token: access_token, fields: "name,gender,location,picture", format: "json" }}).then(function(result) {
var name = result.data.name;
var gender = result.data.gender;
var picture = result.data.picture;
}, function(error) {
alert("Error: " + error);
});
}

Getting error while running my ionic project on devices

i am getting the following error on my device when running it,where as it runs withour erron on browser and only one of my device and check all the devices but same problem
can any one help me
Uncaught TypeError: Object.keys called on non-object ionic.bundle.js:9110
Failed to load resource: net::ERR_CACHE_MISS https://cdn.auth0.com/client/cWQeRf3L4Ength5tIFSrPhrNPUHgO6yQ.js?t1439965186084
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.3.13/$rootScope/infdig?p0=10&p1=%5B%5D ionic.bundle.js:22980
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers','starter.directives', 'auth0',
'angular-storage',
'angular-jwt', 'ngFileUpload','ngResource','ngRoute'])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
.config(function($compileProvider){
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|blob|cdvfile|content):|data:image\//);
})
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
/*File factory for browse*/
.factory("$fileFactory", function($q) {
var File = function() { };
console.log("This is in file factory");
File.prototype = {
getParentDirectory: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURI(path, function(fileSystem) {
fileSystem.getParent(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},
getEntriesAtRoot: function() {
var deferred = $q.defer();
console.log("This is in get Entries in root");
window.webkitrequestFileSystem(1, 0, function(fileSystem) {
var directoryReader = fileSystem.root.createReader();
directoryReader.readEntries(function(entries) {
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
},
getEntries: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURI(path, function(fileSystem) {
var directoryReader = fileSystem.createReader();
directoryReader.readEntries(function(entries) {
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
return File;
})
.factory('Post', function($resource) {
return $resource('http://104.155.192.54:8080/api/logins');
})
.config(function($compileProvider){
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
})
/*This is file browser in ionic */
.factory('Camera', ['$q', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
// Do any magic you need
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['*'];
}
])
.factory('merchantRegisterFactory', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/merchantlogins';
var _loginService = {};
_loginService.getLogins = function() {
return $http.get(urlBase);
};
_loginService.saveLogin = function(login) {
console.log("This is factory is merchantlogins app.js save");
return $http.post(urlBase,login);
};
_loginService.updateLogin = function(login) {
return $http.put(urlBase, login);
};
_loginService.deleteLogin = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _loginService;
})
.factory('addOffer', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/addoffers';
var _addofferService = {};
_addofferService.getOffers = function() {
return $http.get(urlBase);
};
_addofferService.saveOffer = function(login) {
console.log("This is factory is addoffers app.js save");
return $http.post(urlBase,login);
};
_addofferService.updateoffer = function(login) {
return $http.put(urlBase, login);
};
_addofferService.deleteOffer = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _addofferService;
})
.factory('loginsFactory', function($http) {
var urlBase = 'http://104.155.192.54:8080/api/logins';
var _loginService = {};
_loginService.getLogins = function() {
return $http.get(urlBase);
};
_loginService.saveLogin = function(login) {
console.log("This is factory Login is app.js save");
return $http.post(urlBase,login);
};
_loginService.updateLogin = function(login) {
return $http.put(urlBase, login);
};
_loginService.deleteLogin = function(id) {
return $http.delete(urlBase + '/' + id);
};
return _loginService;
})
.run(function($rootScope, auth, store, jwtHelper, $location) {
// This events gets triggered on refresh or URL change
var refreshingToken = null;
$rootScope.$on('$locationChangeStart', function() {
var token = store.get('token');
var refreshToken = store.get('refreshToken');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!auth.isAuthenticated) {
auth.authenticate(store.get('profile'), token);
}
} else {
if (refreshToken) {
if (refreshingToken === null) {
refreshingToken = auth.refreshIdToken(refreshToken).then(function(idToken) {
store.set('token', idToken);
auth.authenticate(store.get('profile'), idToken);
}).finally(function() {
refreshingToken = null;
});
}
return refreshingToken;
} else {
$location.path('/login');
}
}
}
});
})
.config(function($stateProvider, $urlRouterProvider, authProvider, $httpProvider,
jwtInterceptorProvider) {
jwtInterceptorProvider.tokenGetter = function(store, jwtHelper, auth) {
var idToken = store.get('token');
var refreshToken = store.get('refreshToken');
// If no token return null
if (!idToken || !refreshToken) {
return null;
}
// If token is expired, get a new one
if (jwtHelper.isTokenExpired(idToken)) {
return auth.refreshIdToken(refreshToken).then(function(idToken) {
store.set('token', idToken);
return idToken;
});
} else {
return idToken;
}
}
$httpProvider.interceptors.push('jwtInterceptor');
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.addoffer', {
url: "/addoffer",
views: {
'menuContent': {
templateUrl: "templates/addoffer.html",
controller: 'MapCtrl'
}
}
})
.state('app.browse', {
url: "/browse",
views: {
'menuContent': {
templateUrl: "templates/browse.html"
}
}
})
.state('app.playlists', {
cache: false,
url: "/playlists",
views: {
'menuContent': {
templateUrl: "templates/playlists.html",
controller: 'ExampleController'
}
}
})
.state('app.single', {
cache: false,
url: "/playlists/:playlistId",
views: {
'menuContent': {
templateUrl: "templates/playlist.html",
controller: 'ExampleController'
}
}
});
authProvider.init({
domain: 'lokaloffers.auth0.com',
clientID: 'cWQeRf3L4Ength5tIFSrPhrNPUHgO6yQ',
loginState: 'login'
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
})
.run(function(auth) {
// This hooks all auth events to check everything as soon as the app starts
auth.hookEvents();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src * &apos;unsafe-inline&apos;; script-src * &apos;unsafe-inline&apos; &apos;unsafe-eval&apos;">
<title></title>
<!-- compiled css output -->
<link href="css/ionic.app.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above -->
<!-- <link href="css/ionic.app.css" rel="stylesheet">-->
<!-- ionic/angularjs js -->
<script type="text/javascript" src="lib/ionic/js/ionic.bundle.js"></script>
<!-- ngCordova script -->
<script type="text/javascript" src="lib/ngCordova/dist/ng-cordova.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/ng-file-upload/ng-file-upload-shim.min.js"></script>
<script type="text/javascript" src="lib/ng-file-upload/ng-file-upload.min.js"></script>
<!-- Auth0 Lock -->
<script type="text/javascript" src="lib/auth0-lock/build/auth0-lock.js"></script>
<!-- auth0-angular -->
<script type="text/javascript" src="lib/auth0-angular/build/auth0-angular.js"></script>
<!-- angular storage -->
<script type="text/javascript" src="lib/a0-angular-storage/dist/angular-storage.js"></script>
<!-- angular-jwt -->
<script type="text/javascript" src="lib/angular-jwt/dist/angular-jwt.js"></script>
<!--
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqGXcExPSUxrVMpnfBciUejJRU06ZYelE&sensor=true"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&signed_in=true"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC_cy8C8pj5urqUSWERE-qU8NmkoNg6jpk&sensor=true"></script>
-->
<!-- your app's js -->
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/app1.js"></script>
<script type="text/javascript" src="js/directives.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/factory.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
<script type="text/javascript" src="js/countries.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
checkConnection();
}
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
</script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
HI Thanks for the suggession but i solved my problem its the error with ionic CLI ,updated it to latest and it works fine

Android 4.2.2 does not load google maps for my application

I am developing an android application (build with Phonegap) that requires to display the current location of a user and to load KMZ file (with poly lines) on Google Map (use of google map api).
My application loads the map on a specific zoom level (11) and map is centered based on user's current location (reduce data consumption). I noticed that for android OS 4.2.2 the map is not loaded at all, message displayed " access denied to your current position".
On the other hand map is loaded correctly for android OS 4.1.2, 4.3, 4.4 (not get any message).
Is this a security issue/bug for android 4.2.2?
Or it is a bug related to the Phonegap I use to build the APK?
How can I resolve this issue? Is there any configuration I need to do in the mobile?
Thanks
It works fine on Android 4.2.2 or any other supported version. There might be a mistake in your code settings.
I just re-confirmed by creating a sample App.
Steps:
(1) Include Google API Key and Maps jS link in the html header section
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="width=device-width, height=device-height" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_VALUE_&sensor=true"></script>
<title>Hello World</title>
</head>
<body>
<b>Road View</b>
<div id="map-canvas" style="width: 100%; height: 200px"></div>
<b>Street View</b>
<div id="pano" style="width: 100%; height: 200px;"></div>
<b>Live Traffic Update View</b>
<div id="traffic" style="width: 100%; height: 200px;"></div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
(2) In the index.js file declare following function to render maps
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.renderMap();
},
receivedEvent: function(id) {
},
renderMap: function() {
// --- Road View
var fenway = new google.maps.LatLng(42.345573, -71.098326);
var mapOptions = {
center: fenway, zoom: 11
};
var map = new google.maps.Map( document.getElementById('map-canvas'), mapOptions);
// ---- Street View
var panoramaOptions = {
position: fenway,
pov: { heading: 34, pitch: 10 }
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'), panoramaOptions);
map.setStreetView(panorama);
// ---- Live Traffic View
var myLatlng = new google.maps.LatLng(34.04924594193164, -118.24104309082031);
var mapOptions = {
zoom: 13,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('traffic'), mapOptions);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
}
};
app.initialize();
(3) Add permission in the AndroidManifest.xml file.
(4) Set your project API level to your desired version, for instance 4.2.2
(5) Run App on device and it should show three different types of Map Views ( Road, Street and Live Traffic)
This is the JS file code I use to load KML files on map, get current position, display marker:
'use strict';
angular.module('ehunter.controllers', []).
controller('RegionListCtrl', ['$scope', '$http', '$window',
function($scope, $http, $window) {
$http.get('regions.json').success(function(data) {
$scope.regions = data;
});
$scope.openBrowser = function(url){
$window.open(url, "_blank", "location=yes");
}
}])
.controller('RegionViewCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.region = angular.fromJson($routeParams.r);
var map;
var src = "MY_SERVER"+ $scope.region.File;
initialize();
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 11,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
loadKmlLayer(src, map);
}
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: true,
map: map
});
}
getLocation();
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function displayPosition(position) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map
});
marker.setVisible(true);
marker.setMap(map);
map.setCenter(marker.position);
});
}}
}])

Angular need page refresh to load new view

I am trying to develope an app using angular.js and phonegap. My problem is that I have set everything good in my router, but still new views are not loading, so in order to change the view after the route is changed you need to refresh.
Here is my index.html file
<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" lang="en" ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0"/>
<!-- Use the .min version of bootstrap files in production -->
<link rel="stylesheet" type="text/css" href="css/main.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<title>Angular PhoneGap Sample</title>
</head>
<body>
<!-- The following tag is in place of ng-view to use the angular mobile view navigation framework
https://github.com/ajoslin/angular-mobile-nav
-->
<mobile-view/>
<!-- Comment out the following 2 lines to test on the browser-->
<script type="text/javascript" src="cordova-2.7.0.js"></script>
<script src="lib/index.js"></script>
<!-- In production use min versions -->
<script src="lib/jx.min.js"></script>
<script src="lib/angular.js"></script>
<script src="lib/angular-mobile.js"></script>
<script src="lib/mobile-nav.js"></script>
<script src="lib/jquery.min.js"></script>
<!-- // <script src="lib/angular-route.min.js"></script>
// <script src="lib/angular-resource.js"></script>
// <script src="lib/ui-bootstrap-tpls-0.11.0.min.js"></script> -->
<script src="app/app.js"></script>
<script src="app/main/mainController.js"></script>
<script src="app/about/aboutController.js"></script>
<script src="app/about/playController.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
And here is the app.js
'use strict';
function jsonp_callback(data) {
// returning from async callbacks is (generally) meaningless
console.log(data.found);
}
var myApp = angular.module('myApp', ['ajoslin.mobile-navigate', 'ngMobile']);
myApp.config(function ($compileProvider){
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
})
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
})
.when('/play', {
templateUrl: 'app/play/play.html',
controller: 'PlayCtrl'
})
.when('/settings', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
})
.when('/options', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'app/about/about.html',
controller: 'AboutCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
myApp.run(function($rootScope, $location){
// $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
// if(rejection === 'not-authorized'){
// $location.path('/');
// }
// if(rejection == 'authorized'){
// $location.path('/home');
// }
// });
var history = [];
$rootScope.$on('$routeChangeSuccess', function() {
history.push($location.$$path);
});
$rootScope.history = history;
});
And I tried to change route both with a hyperlink href="#/play" and within the controller$location.path('/play');` but nothing works ;/
I think, nothing will work until you inject ngRoute. You have to add that file too in Index.html.
angular-route.js is now separate file. You manually have to inject that file in order to run your defined routes.
One more thing with 'a' html link tag you have to write href="#play"...
I'm not sure about mobile-view. so use ng-view if it doesnt work.
At the end I was able to get it running with angular-mobile, ngRoute, and no hrefs. Instead of them I used this function on ng-click:
$scope.slidePage = function (path,type) {
navSvc.slidePage(path,type);
};
with this service, of course:
myApp.factory('navSvc', function($navigate) {
return {
slidePage: function (path,type) {
$navigate.go(path,type);
},
back: function () {
$navigate.back();
}
}
});

Categories

Resources