Page refresh with AngularJs templates - javascript

I am using ngRoute to serve up templates in my app. So I will do something like this
$routeProvider.when('/', { templateUrl: '/templates/search.html', controller: 'SearchController' })
.when('/SearchResults', { templateUrl: '/templates/searchResults.html', controller: 'SearchResultsController' })
.when('/Problem', { templateUrl: '/templates/problem.html', controller: 'ProblemController' });
Say the user goes to /Problem and then hits the refresh button in the browser they are obviously going to get a 404 error because /Problem doesn't exist on the server. Is there a standard way of handling this in angular?

That's why you add a # before your hyperlink as shown in the angularjs tutorial: https://docs.angularjs.org/tutorial/step_07
So for example:
# will refer to the index site, and that's where angularjs will do your wished routing, even if the page is being refreshed, bookmarked, ...

Related

Angular $route change url based on route

I'm writing a simple product information management app using angular js. To keep my app as modular as possible i've split it into multiple modules with one module "pim" as startpoint. For each module I want to have a different route, so that it is easy to plug in a new module or remove it without having to maintain a huge route in the pim module config.
Currently I have two routes (the first route):
(function(){
angular
.module("pim")
.config(router)
function router($routeProvider){
$routeProvider
.when("/",{
templateUrl: "view/info.html",
controller: "pimController"
})
.when("/info",{
templateUrl: "view/info.html",
controller: "pimController"
})
.when("/alcohol",{
templateUrl: "view/alcohol.list.html",
controller: "alcoholController"
});
}
})();
The second route
(function(){
angular
.module("alcohol")
.config(router)
function router($routeProvider){
$routeProvider
.when("/alcohol/list",{
templateUrl: "view/alcohol.list.html",
controller: "alcoholController"
})
.when("/alcohol/info",{
templateUrl: "view/alcohol.info.html",
controller: "alcoholController"
});
}
})();
As you can see /alcohol has a templateUrl and a controller, the same as /alcohol/list, but i want to know if there is a simple (standard) way to change to another URL for example /alcohol/list, so that I do not have to repeat the templateUrl and controller and keep this information in the alcohol module, where it belongs.
For example
.when("/alcohol",{
routeTo: "/alcohol/list"
})
Thank you for your help
SOLVED
The option to redirect exists, did not look in the $routeProvider documentation well enough:
.when("/alcohol",{
redirectTo:"/alcohol/list"
});
The code above works
You can use $routeProvider's redirectTo route map.
.when("/alcohol", {
redirectTo: "/alcohol/list"
});
Read more: https://docs.angularjs.org/api/ngRoute/provider/$routeProvider

Target route while using angular routing

I am trying to integrate angular routing with and existing app.
The webapp uses angular already but does not use routing per se.
I was able to manually integrate routing and my routing js looks like following
phonecatApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/list1.jsp', {
templateUrl: '/mycontext/templates/list1.jsp',
}).
when('/list2.jsp', {
templateUrl: '/mycontext/templates/list2.jsp',
}).
otherwise({
});
}]);
After using routing for couple of files I found a common pattern, my #path was very similar to the path of the template. Thus I was wondering if there is any way to get the next url in the route itself so that I can dynamically create a fallback. For example
otherwise({
nextURL = $nxtURL;
redirectTo: '/mycontext/templates/'+nextURL;
});

Why is my default page different when opened in emulator vs browser? (ionic/angular ui)

I'm using ionic to create a mobile app. I'm new to ionic/angularjs so this is a huge learning curve...
When I open my app in browser by using a fresh ionic serve command, the default page is my login page as I would expect based on the $urlRouteProvider.otherwise command. When I use cordova emulate android the default app is my cards page which I don't understand why... What's going on and how do I set the default state to be my login page? (PS I say I used a 'fresh' ionic serve command meaning it wasn't already open in a browser and simply refreshing the last page.)
Here is the relevant sections of my app.js
angular.module('starter', ['ionic', 'starter.controllers'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'CardsCtrl'
})
.state('app.cards', {
url: "/cards",
views: {
'menuContent' :{
templateUrl: "templates/cards.html",
controller: 'CardsCtrl'
}
}
})
.state('app.login',{
url:'/login',
views:{
'menuContent':{
templateUrl:'templates/login.html',
controller: 'LoginCtrl'
}
}
});
$urlRouterProvider.otherwise('/app/login');
})
My CardsCtrl is just an array so that I can use ng-repeat, there is no logic that would route it to login page. My LoginCtrl is currently an empty controller.
Based on this information why is this routing the default page
Every information you have provided is just fine. Since it is working fine in your web browser, you should look at options of debugging your app on device.
Most trivial way is to look at logcat. It will display all error messages that occured at runtime in your terminal. Using logcat is very easy. This is one of the resources: http://wildermuth.com/2013/4/30/Debugging_PhoneGap_with_the_Android_Console

Angular JS Routing - Links inside SPA

I have created a project with index.html with certain links to other pages. My routing works as intended but I'm wondering what's the best approach to go with when it comes to links on other pages.
To clarify it:
My index.html page has routes:
Feed
Bblog
Marketplace
Recruiting
Adverts
Now what I'm curious about is how do I for example route links inside these pages.
For example, my Bblog page has tabs which I want to be opened inside the same page. Now for example whenever I click some tab link, it redirects me to my index.html since my .otherwise route is set to /.
Not sure what engine or library you're using for your routing. Though I faced the same requirement not too long ago.
We're using ui-router for our routing. It's very similar to Angulars routing.
A snippet from our routing table contains something similar to this.
$stateProvider
.state('home', {
url: '/',
templateUrl: '/views/index',
})
.state('orders', {
url: '/orders',
templateUrl: '/views/orders',
})
.state('orderdetail', {
url: '/orders/detail/:id',
templateUrl: '/views/orderdetail',
})
.state('orderdetail.address', {
url: '/:addressId',
templateUrl: '/views/orderdetail',
})
Essentially you use the .dot notation to separate nested views. So the orderdetail.address is nested inside the orderdetail
This means that the routing above will go something allow you to see an overview of order details at /orders/detail/myOrderId and drill further in to, say, an address by visiting /orders/detail/myOrderId/myaddressId
If you're using ui-router then you will get more info on nested views on this link
If you're using angular ngRoute then the [ngRoute][3] docs and supporting plunker demonstrate how to stack up the routes.
So (from the plunker) -
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookController',
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
})
.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: 'ChapterController'
});
this will give you /book/myBookId and /book/myBoodId/ch/myChapterId

AngularJs reload page instead only load view

I have a simple app in AgularJS. I need to load view in route
$routeProvider.when('/articles/:url', {
templateUrl: 'partials/article.html',
controller: ArticleCtrl
});
But if i click on
Page reloads and after reload Angular try to load partials/article.html view, but fails on error "NetworkError: 404 Not Found - http://localhost:3000/clanky/partials/article.html"
I know that I can use "../partials/article.html" insted "partials/article.html", but I mean that isn't the core of problem.
There are my routes:
blog.config([
'$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
templateUrl: 'partials/main.html',
controller: MainCtrl
});
$routeProvider.when('/login', {
templateUrl: 'partials/login.html',
controller: LoginCtrl
});
$routeProvider.when('/backend', {
templateUrl: 'partials/backend.html',
controller: BackendCtrl
});
$routeProvider.when('/articles/:url', {
templateUrl: 'partials/article.html',
controller: ArticleCtrl
});
return $routeProvider.otherwise({
redirectTo: '/'
});
}
]);
P.S.
If I try go to the any other route, for example, login, it partialy works, but reload is still here.
Thanks for yours answers
seems that I've got the same problem as you.
I don't know how to handle this but I think that's because the page was reloaded.
When you are not setting the html5Mode to true, then will be # at the url, and if you reload the page, the # will track the information to the $scope to work with the htmlHistory api so that the app can work properly even with the page refresh.
But once you set the html5Mode to true, then there's no # to store any $scope information, and when the page reload, angular can not found the accordingly scope so it return 404.
You can check $location section on angularjs guide, it has a section explaining why this happen.
Page reload navigation
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API, $window.location.href.
Hope this can be helpful for you, and if you got any better answer, please let me know, I'm also waiting for the right way to solve it.
Start your templateUrl with a slash:
templateUrl: '/partials/article.html'
instead of
templateUrl: 'partials/article.html'

Categories