AngularJS + PhoneGap, routing doesn't work - angularjs

I am having issue with routing on mobile phone when I use phonegap.
Routing on browser works but on mobile devices is not working.
If there is any question, I can provide more code.
route.js:
app.config(['$routeProvider','$locationProvider','$compileProvider', function($routeProvider,$locationProvider,$compileProvider) {
$routeProvider
.when('/', {
templateUrl: '../login.html',
controller: 'loginController'
})
.when('/home',{
templateUrl:'../home.html',
controller:'homeController'
})
.when('/profile', {
templateUrl:'../myprofile.html',
controller:'profileController'
})
.when('/reservations',{
templateUrl:'../reservations.html',
controller:'reservationController'
})
.when('/ordernow',{
templateUrl:'../ordernow.html',
controller:'ordercontroller'
})
.otherwise({
redirectTo: "/home"
});
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
}]);

After few hours of struggling:
solution: remove "../" from templateUrl

I guess this particular issue might have been fixed long ago, but I was having similar trouble with angular 1.6 and cordova android app.
I was using the correct path for templateUrl but still routing was not working.
After spending a whole day looking through different documentations and trying out different things i stumbled upon a small mystery. I was debugging the cordova app using google chrome inspect and found the app URL to be
file:///android_asset/www/index.html#!/
When i navigate to another page, I get the URL
file:///android_asset/www/index.html#!/#%2faccounts
Then while investigating that, I stumbled upon this
I used the following while configuring the router
$locationProvider.hashPrefix('');
This seemed to fix the problem for me. Code snippet below:
var prakriya = angular.module("prakriya",["ngRoute"]);
prakriya.config(function($routeProvider, $locationProvider){
$locationProvider.hashPrefix(''); //Added Line here
$routeProvider
.when("/", {
templateUrl: "templates/workspace.html",
controller: "workspace"
});
});

Related

How to : Angularjs route refresh

I trying to make an application that contains multiple views as template. The templates are under the js/app/pages/ folder. And I have 2 templates to show and route. My routing section is:
var app = angular.module("myApp", ['ngRoute', 'ngMaterial']);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/Page', {
templateUrl: 'js/app/pages/Page.html',
controller: 'pageController',
reloadOnSearch: false
})
.when('/Settings', {
templateUrl: 'js/app/pages/Settings.html',
controller: 'settingsController',
reloadOnSearch: false
})
.when('/Admin', {
templateUrl: 'js/app/pages/Admin.html',
controller: 'adminController',
reloadOnSearch: false
})
.otherwise({
redirectTo: '/Page'
});
$locationProvider.html5Mode(true);
});
And my html file contains
<div id="menu"></div>
<div ng-view></div>
Menu div contains menu elements that route me between the pages. For example, when I run this site on browser, URL will be localhost/Page, and when I click the settings button URL change with localhost/Settings. But when I press the F5 button in my keyboard. Page gives me error The resource cannot be found..
I search on the internet "how to refresh routing page in angularjs" and find some solutions but I couldn't make them work for me. I tried $route.reload() and $routeUpdate() method but that does not work for me. Maybe I'm wrong in something.
If you are using Apache server this should work run this in terminal
sudo a2enmod rewrite && sudo service apache2 restart
works for me
Solved! I couldn't manage refresh with ngRoute. Then i convert it into ui-router. I declare the states by urls. And the refresh is working. Thanks for comments and answers. Maybe this will help someone.
Actually when you are pressing F5 from keyboard, it is hitting to your server for that page, not angular because you don't have any # sign between your URL. For angular, URL should be like as - localhost/#/Page
Use html5mode
A great article about it here
to init its very simple
.config(function($routeProvider, $locationProvider) {
// other routes here
$locationProvider.html5Mode(true);
});
When you "reload a page", you whole app will reinit again. That means if you are not on the main page, and the sub route you are at missing some data, you will likely get an error.
You should look into resolve attribute for routes, so for example,
.when('/Settings', {
templateUrl: 'js/app/pages/Settings.html',
controller: 'settingsController',
reloadOnSearch: false,
resolve: {
resourceone: function(){return whatsneeedtoberesolvehere;}
}
})
that way no matter where your app is reloaded, it will have the necessary data to boot the page
Just keep the # in URL, you don't have to put extra effort to manage reloads etc. you can think a "#" in URL represent a specific state in single page application.
Otherwise it can be managed by module rewriting, that map the url with hashed version URL internally for AngularJs app.

Why won't AngularJS routing work in Wordpress?

I am pulling my hair out trying to get this to work. It works just fine by itself but once the Angular code is loaded in Wordpress, Angular seems to always think I'm at http://example.com/ when I am at any other url (e.g. http://example.com/login). I have a feeling it has something to do with the .htaccess, but am not certain. Below is just a piece of the Angular code, everything loads perfectly fine, it's just the routing that is messed up.
var app = angular.module('app', ['ngRoute']).config(function($routeProvider){
$routeProvider.when('/login', {
templateUrl: wpurl + '/my/app/assets/login.htm',
controller: 'LoginController'
});
$routeProvider.when('/', {
templateUrl: wpurl + '/my/app/assets/home.htm',
controller: 'HomeController'
});
$routeProvider.otherwise({ redirectTo: '/login'});
});
If I visit /login the view for / will always be displayed. Also for whatever reason, the login view IS displayed only when visiting example.com/login/#/login, and am also redirected to that url when it's supposed to only redirect to /login. Any ideas??
Edit: Also should mention this is being loaded via plugin

AngularJS routing not working properly in PhoneGap

I have been beating my head against the wall trying to figure out why angularJS routing won't work in phonegap for me. I have all the files setup correctly and i don't receive any errors. I'm trying to change the url using the $location.url service directly from angular. So when you tap on a div the controller will have $location.url("profile") for example and nothing will happen. I tried the solution found in this stackoverflow but that's not working for me. Am I doing something wrong, or is there a better way to be approaching this? Following is the routing I have setup
var app = angular.module("App", ["hmTouchevents"])
.config(function($routeProvider) {
$routeProvider
.when("/index.html", {
templateUrl: "/views/login.html",
controller: "loginCtlr"
})
.when("/landing", {
templateUrl: "/views/landing.html",
controller: "landingCtlr"
})
.when("/single-view/:id", {
templateUrl: "/views/single-view.html",
controller: "singleViewCtlr"
})
.when("/restaurant", {
templateUrl: "/views/restaurant-info.html",
controller: "restaurantCtlr"
})
.when("/profile/:id", {
templateUrl: "/views/profile.html",
controller: "profileCtlr"
})
.when("/lists/:list", {
templateUrl: "/views/lists.html",
controller: "listsCtlr"
})
.when("/follow/:type", {
templateUrl: "/views/follow.html",
controller: "followCtlr"
});
});
A sample controller would be:
app.controller("listsCtlr", ["$scope", "$location", function($scope, $location){
$scope.goTo("profile");
}]);
As always any help is much appreciated.
I had a problem similar to this tonight. The core issue here is that PhoneGap doesn't have a web server built in. If you're developing locally, you probably are using a web server, so you can do something like: http://localhost/#/profile and the routing will work.
However, PhoneGap loads your code with a file:// URL, not http://. If you do $location.url("profile") you're replacing the entire URL with just file://profile, which doesn't exist. Same thing if you use a link like this: My Profile
The solution is to somehow get your links to point to the right place. If you're using $location.url() you can prefix it with your file path: $location.url( window.location + "#/profile" )
If you're just making a link, you should be able to get away with taking off the leading slash to make it a relative URL: My Profile becomes My Profile
Had the exact same issue... I was able to fix this easily by adding the following code to the head of my index.html file.
<base href="/android_asset/www/" />
Hope this helps.
in your controller try...
$location.path('/profile');
After much tinkering, here's what worked for me!
If you can use $location.path() within the controller, it should work as expected, but if you need to use href-style links, you can build the links off the angular "base" page (e.g. main.html):
Link To Profile

chrome removes url path angular

i got this problem with angular when I open the site in Chrome
_localhost/angular/_
the url changes to
_localhost/#_
however in firefox everything is as expected
I asume its caused by the routeProvider
var Angapp = angular.module('angApp', []).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'partials/main.html',
controller: mainCtrl
})
.when('/:catId', {
templateUrl: 'partials/category.html',
controller: categoryCtrl
})
.when('/detail/:detId', {
templateUrl: 'partials/detail.html',
controller: detailsCtrl
})
.otherwise({
redirectTo: '/'
});
}]);
I hope someone can help me with this and explain what is happening what did i miss.
thanks in advance.
EDIT:
when I add
.....
config(['$routeProvider','$locationProvider', function($routeProvider. $locationProvider){
.......
$locationProvider.html5Mode(true);
the routing breaks completely in Chrome and firefox
_localhost/angular/#%2Flink_
when i remove the "#%2F" and reload the page I get a 404 as return
when i hit backspace then the site loads correctly!
Please be sure that your browser supports HTML5. For browsers that don't support HTML5 history API AngularJS will automatically fall back to hasbang URLs so no way to "remove" the hash(#).

Unable to refresh page when using Angular, jQM, and Adapter

I'm working on a web page that is using Angular, jQuery Mobile, and the jQuery Mobile Angular adapter by tigbro. I have everything up an running and it works great except for one issue and that is if at any point if you refresh the page using the browser's refresh button it will give a 404 error as if it doesn't understand the route anymore. I'm not sure where the issue might be since it gets a little confusing with the two frameworks and the adapter working together and I'm new to all of these technologies.
IE happens to be the only browser this doesn't happen in and the difference seems to be in the url. Here is what it looks like when you browse to a page in IE:
http://site.com/SalesManagement/SalesManagementIndex.aspx#!/ViewNotes/4
Here is what it looks like when you browse to the same page in another browser like Chrome:
http://site.com/SalesManagement/ViewNotes/4
If you go to the first url in Chrome it will load the page and then rewrite the url to the 2nd one.
Below is my routing configuration:
var SalesManagementApp = angular.module('SalesManagementApp', [])
SalesManagementApp.config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {
$routeProvider
.when('/Search', { templateUrl: 'Views/GrowerSearchView.aspx' })
.when('/SearchResults', { templateUrl: 'Views/GrowerResultsView.aspx' })
.when('/ViewNotes/:growerIndexKey', { templateUrl: 'Views/NotesHistoryView.aspx' })
.when('/EditNote/:growerIndexKey/:noteIndexKey', { templateUrl: 'Views/UpsertNoteView.aspx' })
.when('/AddNote/:growerIndexKey', { templateUrl: 'Views/UpsertNoteView.aspx' })
.when('/', { templateUrl: 'Views/GrowerSearchView.aspx' })
.otherwise({ templateUrl: 'Views/GrowerSearchView.aspx' });
} ]);
I've read some about html5 mode verse hashbang mode but setting html5 mode to off or on in the configuration just made my routing not work at all. Any help would be much appreciated.
I figured this out thanks to a similar question on the github site for the adapter: https://github.com/opitzconsulting/jquery-mobile-angular-adapter/issues/163
The fix for this is to disable html5Mode in angular and prefix your links with the # character. This makes your urls a little uglier as you are no longer using the html5 history API but in my case that doesn't matter. Optionally you can specify a hash prefix (by default it seems to be !) but I set mine to empty string. I couldn't find any documentation telling me why this is useful but its important to know what the prefix is so you can properly set your links.
Below is my updated routing configuration. Notice I now inject the $locationProvider.
var SalesManagementApp = angular.module('SalesManagementApp', [])
SalesManagementApp.config(['$routeProvider', '$compileProvider', '$locationProvider', function ($routeProvider, $compileProvider, $locationProvider) {
$locationProvider.html5Mode(false).hashPrefix("");
$routeProvider
.when('/Search', { templateUrl: 'Views/GrowerSearchView.aspx' })
.when('/SearchResults', { templateUrl: 'Views/GrowerResultsView.aspx' })
.when('/ViewNotes/:growerIndexKey', { templateUrl: 'Views/NotesHistoryView.aspx' })
.when('/EditNote/:growerIndexKey/:noteIndexKey', { templateUrl: 'Views/UpsertNoteView.aspx' })
.when('/AddNote/:growerIndexKey', { templateUrl: 'Views/UpsertNoteView.aspx' })
.when('/', { templateUrl: 'Views/GrowerSearchView.aspx' })
.otherwise({ templateUrl: 'Views/GrowerSearchView.aspx' }); // jQuery Mobile seems to ignore the / and just use .otherwise.
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
if (!localStorage.SessionInfo)
window.location = '/Login.aspx';
} ]);
My links now look like: #/ViewNotes/{{growerIndexKey}}

Resources