Angular JS Routing - Links inside SPA - javascript

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

Related

AngularJs ui-sref not working, and state abstracts

For some reason my ui-sref links are not updating and allowing me to change state on my app.
Can someone please tell me what i have done wrong? I have attached a plunkr link for the full code
App.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
'use strict';
// defaults to home
$urlRouterProvider.otherwise('/home');
// states
$stateProvider
.state('app', {
url: '',
abstract: true,
templateUrl: 'app.html',
controller: 'AppController'
})
.state('app.home', {
url: '/home',
templateUrl:'home.html',
controller: 'HomeController'
})
.state('app.settings', {
url: '/settings',
templateUrl: 'settings.html',
controller: 'SettingsController'
});
}]);
http://plnkr.co/edit/m77wrOU0sMLG0fmicTaK
If i navigate to /home, this works and if i go to /settings that also works. but the links are not generated on my pages?
Also, if i want to have multiple layouts, say i would like an admin layout and a normal user layout, maybe the admin layout would hide a few items on the page and show others, would this be best to be done using routing? I have about 6 different parts of the page, currently not setup as views, but i wonder if this is the route i should go down?
Is there anything wrong with having more than 1 abstract state in your stateProvider, or is that stupid?

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

AngularJS ui router - How can I ignore certain routes?

I am using ui-router in my web application. On one of my views I have a canvas which I am drawing to using a 3rd party library. This library attempts to dynamically load images (HTTP GET). My problem is ui.router's $urlRouterProvider is handling the routing and therefore all image requests are resulting in a 404 error.
How is this typically handled in an AngularJS application? Is there a way to ignore specific routes?
My route configuration looks like this:
app.config(function($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/");
//
// Now set up the states
$stateProvider
.state('main', {
url: "/",
templateUrl: "partials/main.html"
})
.state('login', {
url: "/login",
controller: 'LoginCtrl',
templateUrl: "partials/login.html"
})
.state('signup', {
url: '/signup',
controller: 'SignupCtrl',
templateUrl: 'partials/signup.html'
})
});
I'd like to ignore any routes matching '/assets/*' and allow those requests to pass right through to the server.
This is typically dealt with at the server level (Express here):
app.use express.static(path.join(__dirname, "assets"))
So that any url with "/js/app.js" will be rendered as an asset. It shouldn't be something angular has to deal with. I've got a very similar $stateProvider that I grabbed off of some boilerplate and there's no special case for assets in the $stateProvider.
Do you have script or img tags inside of a controller or view boundary? That could explain what you are seeing.

Page refresh with AngularJs templates

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, ...

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