AngularJS ui route hash prefix - javascript

I am using AngularJS ui route for routing I want to remove # (hash from URL). I am using this code and also using (base href="/") in my index.html file. It's working fine but when I refresh the page like (http://0.0.0.0:3000/athletepersonalinfo) it's giving me an error.
.config(function($stateProvider,$locationProvider) {
$locationProvider.html5Mode({ enabled: true, requireBase: false })
$stateProvider
.state('/', {
url: '',
templateUrl:HTML.HOME,
controller: 'homeController as home'
})
.state('home', {
url: '/',
controller: 'homeController as home',
templateUrl: HTML.HOME
})
.state('athletepersonalinfo', {
url: '/athletepersonalinfo',
controller: 'athleteProfileInfo',
templateUrl: HTML.ATHLETE_PERSONAL_INFO,
authenticate: true
})

When you hit refresh the server actually tries to find if the given route has been defined /athletepersonalinfo. To actually remove the # from the url you will have to include a get(/*) route which would always return your index.html page. This route should be after all other routes. Now what this means is your index.html will be served whenever no routes is defined than in your client side angular will handle which view to load. Few points to note when making such chages
Since any unresolved get could return your index.html make sure your routes are meaningful like all your assets start with /assets/ path, all your api calls start with /api/ .
The benefit in doing so is if you get a 404 on some assets or an api call you would still get your index.html which is wrong. But with this approach all you need to do is set a route something like this
app.get('/:url(api|assets)/*',function(req,res){
res.status(400).send("Not Found")
});
app.get('/*',function(req,res){
res.sendFile('index.html');
});
Make sure the * route is defined after all other routes else you will keep getting index.html for every request.
Hope this helps.

Related

UI router cannot resolve state error message

I am working on angular application at the moment, using ui-router and I am getting the following error message.
Error: Could not resolve 'static.about' from state 'static'
and I am not sure why. What I am wanting to achieve is to have 2 sections to my application, the static section, homepage, about, login, register and the app side which would things like dashboards, user profiles etc I thought I would need to set up my ui-router like this,
app
.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
// any unknown URLS go to 404
$urlRouterProvider.otherwise('/404');
// no route goes to index
$urlRouterProvider.when('', '/home');
// use a state provider for routing
$stateProvider
.state('static', {
url: '/home',
templateUrl: '',
views : {
header : {
templateUrl : 'app/components/shared/header.html'
},
main: {
templateUrl : 'app/components/home/views/home.view.html'
}
}
})
.state('static.about', {
// we'll add another state soon
url: '/about',
templateUrl: 'app/components/about/views/about.view.html',
})
.state('app', {
abstract: true,
templateUrl: ''
})
.state('app.dashboard', {
url: 'app/dashboard',
templateUrl : '',
})
}]);
However this returns the error already mentioned. The reason I am wanting to set it up like this that the 2 sides to application also have very different layouts, so I figured that I should be able push different layouts into my ?
The biggest problem I am having however is the error, and secondly the links being generated, when I click on about it should go to /about, however it is going to /home/about.
All I am wanting to achieve in the early stages is for my "static" pages to share a nav and have interchangeable main section, and for "app" pages to have a completly new layout/parent template
You need to set the parent property on the children views.
.state('static.about', {
url : '/about',
templateUrl : 'app/components/about/views/about.view.html',
parent : 'static'
})
Also check the answer to this question Angular ui-router : Parent & Child Views.
I guess that when you do $state.go(static.about) it just goes to homepage since you are doing an otherwise or something similar.
Like : $urlRouterProvider.when('', '/home');
Angular-Ui-Router resolves the main route when something isn't okay.
Also pay attention to the extra , you are adding at the end of templateUrl.
The above construction of states is ok. I created a plunker to demonstrate it here
In a root state 'static' we just do not use templateUrl.. it would be skipped anyhow, because we do define views : {}
.state('static', {
url: '/home',
// we want to have views : {} so avoid this shorthand template
// templateUrl: '',
views: {
header: {
templateUrl : 'app/components/shared/header.html',
},
main: {
templateUrl : 'app/components/home/views/home.view.html',
}
}
})
And a child state 'static.about' can use '^' leading sign, to reset its url from root
.state('static.about', {
// here we use a switch to inform - this url starts from root
//url: '/about',
url: '^/about',
templateUrl: 'app/components/about/views/about.view.html',
})
And with these calls, all is working
<a ui-sref="static">
<a ui-sref="static.about">
Check it in action here
The Error message:
Error: Could not resolve 'static.about' from state 'static'
Usually happens, if we have a typoe in state definition (or calling side). But that is not the issue. Or if we omit to load definition file...
To me it seems that, you don't want to define a completely new UI when going to static.about but use the header from static.
Remove the templateUrl from static.about
Add a property view that should be an object with a property called "main#static" and the value should be another object with your templateUrl.
More info: https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views

Cannot get on refresh angular js

All my route in app.js working fine, on refreshing page.
I have to create a route with special params like this :
http://localhost:9000/bureaux-a-louer/rhone/lyon/69003/filters?lat=45.7593054&lng=4.841594600000008
From the homepage to this route it works well , i can get all parameters. But when i refresh this i got
Cannot get /bureaux-a-louer/rhone/lyon/69003/filters?lat=45.7593054&lng=4.841594600000008
Looks like the dot parameters breaks it... because when i put a comma in lat/lng parameters it's working fine...
If someone have an idea to fix it.
It's an Angular application on 1.5.7 , with ng route param like this :
.when('/bureaux-a-louer/:cp/:city/:zipcode/:filters', {
templateUrl: 'views/search/search.html',
controller: 'SearchCtrl',
controllerAs: 'search',
authorized: false,
footer: false,
skipAuthorization: true
})
And i use NodeJS with grunt

angular route with asp.net MVC remove hash # on url

I'm developing a web application using ASP.NET MVC and AngularJS with ngRoute module. The configuration works fine but URLs contain #/ and I would like to remove them. I know the point is adding $locationProvider.html5Mode(true); and <base href="/"> in the <head> but there is some conflict with server side routing and I can't get it work.
This is the route provider
$routeProvider
.when("/", {
templateUrl: "Home/Phones",
controller: "firstController"
})
.when("/phone", {
templateUrl: "Home/Phone",
controller: "secondController"
})
Pages can be normally accessed through http://localhost/test/#/ and http://localhost/test/#/phone.
Now if I add $locationProvider.html5Mode(true); and <base href="test"> in the header section of index page I can access the default page at http://localhost/test/ but the page is empty. Trying to access and I get an error at http://localhost/test/phone fires 404 page not found.
So... how to solve the first problem? Console doesn't show any error, don't know what to try...
I guess I should at least change my RouteConfig.cs, not it contains the default
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The browser is requesting an asset /test/phone but that doesnt exist. In the case of 404s within a Single Page App using html5Mode you need to configure your webserver to serve the index.html on all "404"s

jQuery is loading my root route and all the scripts again through XHR

I'm stuck with this problem for a few days and I think now is the time to get some help.
I'm updating my Angular app from v1.3.0-beta.17 to v.1.3.x (head) and now I'm getting this message WARNING: Tried to load angular more than once.. The weird thing I noticed is that jQuery is loading the / route and all my scripts again afterwards through AJAX. See:
Also this problem only occurs for one route (described below). Anyone would have any ideas on why jQuery is behaving like this?
Here's my routes:
javascript
$routeProvider
.when('/', {
'controller': 'loading',
'templateUrl': versioning('/assets/template/system/blank.html')
})
.when('/dashboard/:dashboard_id', { // this is the route with error
'controller': 'loading',
'templateUrl': versioning('/assets/template/dashboard/dashboard.html')
})
.when('/dashboard/:dashboard_id/widget', {
'controller': 'loading',
'templateUrl': versioning('/assets/template/dashboard/widget.html')
})
.when('/dashboard/:dashboard_id/widget/:widget_id', {
'controller': 'loading',
'templateUrl': versioning('/assets/template/dashboard/widget.html')
})
//...
.otherwise({
'templateUrl': versioning('/assets/template/system/404.html')
});
This is usually that you have a url pointing to a file that does not exist or it could be that you are missing the end of and html tag or something that causes your html to be invalid. Double check all your url paths and your html is correct.

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.

Categories