$location / switching between html5 and hashbang mode / link rewriting - angularjs

I was under the impression that Angular would rewrite URLs that appear in href attributes of anchor tags within tempaltes, such that they would work whether in html5 mode or hashbang mode. The documentation for the location service seems to say that HTML Link Rewriting takes care of the hashbang situation. I would thus expect that when not in HTML5 mode, hashes would be inserted, and in HTML5 mode, they would not.
However, it seems that no rewriting is taking place. The following example does not allow me to just change the mode. All links in the application would need to be rewritten by hand (or derived from a variable at runtime. Am I required to manually rewrite all URLs depending on the mode?
I don't see any client-side url rewriting going on in Angular 1.0.6, 1.1.4 or 1.1.3. It seems that all href values need to be prepended with #/ for hashbang mode and / for html5 mode.
Is there some configuration necessary to cause rewriting? Am I misreading the docs? Doing something else silly?
Here's a small example:
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.3/angular.js"></script>
</head>
<body>
<div ng-view></div>
<script>
angular.module('sample', [])
.config(
['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
//commenting out this line (switching to hashbang mode) breaks the app
//-- unless # is added to the templates
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
template: 'this is home. go to <a href="/about"/>about</a>'
});
$routeProvider.when('/about', {
template: 'this is about. go to <a href="/"/>home</a'
});
}
])
.run();
</script>
</body>
Addendum: in re-reading my question, I see that I used the term "rewriting" without an abundance of clarity as to who and when I wanted to do the rewriting. The question is about how to get Angular to rewrite the URLs when it renders paths and how to get it to interpret paths in the JS code uniformly across the two modes. It is not about how to cause a web server to do HTML5-compatible rewriting of requests.

The documentation is not very clear about AngularJS routing. It talks about Hashbang and HTML5 mode. In fact, AngularJS routing operates in three modes:
Hashbang Mode
HTML5 Mode
Hashbang in HTML5 Mode
For each mode there is a a respective LocationUrl class (LocationHashbangUrl, LocationUrl and LocationHashbangInHTML5Url).
In order to simulate URL rewriting you must actually set html5mode to true and decorate the $sniffer class as follows:
$provide.decorator('$sniffer', function($delegate) {
$delegate.history = false;
return $delegate;
});
I will now explain this in more detail:
Hashbang Mode
Configuration:
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(false)
.hashPrefix('!');
This is the case when you need to use URLs with hashes in your HTML files such as in
link
In the Browser you must use the following Link: http://www.example.com/base/index.html#!/base/path
As you can see in pure Hashbang mode all links in the HTML files must begin with the base such as "index.html#!".
HTML5 Mode
Configuration:
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true);
You should set the base in HTML-file
<html>
<head>
<base href="/">
</head>
</html>
In this mode you can use links without the # in HTML files
link
Link in Browser:
http://www.example.com/base/path
Hashbang in HTML5 Mode
This mode is activated when we actually use HTML5 mode but in an incompatible browser. We can simulate this mode in a compatible browser by decorating the $sniffer service and setting history to false.
Configuration:
$provide.decorator('$sniffer', function($delegate) {
$delegate.history = false;
return $delegate;
});
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true)
.hashPrefix('!');
Set the base in HTML-file:
<html>
<head>
<base href="/">
</head>
</html>
In this case the links can also be written without the hash in the HTML file
link
Link in Browser:
http://www.example.com/index.html#!/base/path

Fur future readers, if you are using Angular 1.6, you also need to change the hashPrefix:
appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('');
}]);
Don't forget to set the base in your HTML <head>:
<head>
<base href="/">
...
</head>
More info about the changelog here.

This took me a while to figure out so this is how I got it working - Angular WebAPI ASP Routing without the # for SEO
add to Index.html - base href="/">
Add $locationProvider.html5Mode(true); to app.config
I needed a certain controller (which was in the home controller) to be ignored for uploading images so I added that rule to RouteConfig
routes.MapRoute(
name: "Default2",
url: "Home/{*.}",
defaults: new { controller = "Home", action = "SaveImage" }
);
In Global.asax add the following - making sure to ignore api and image upload paths let them function as normal otherwise reroute everything else.
private const string ROOT_DOCUMENT = "/Index.html";
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var path = Request.Url.AbsolutePath;
var isApi = path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase);
var isImageUpload = path.StartsWith("/home", StringComparison.InvariantCultureIgnoreCase);
if (isApi || isImageUpload)
return;
string url = Request.Url.LocalPath;
if (!System.IO.File.Exists(Context.Server.MapPath(url)))
Context.RewritePath(ROOT_DOCUMENT);
}
Make sure to use $location.url('/XXX') and not window.location ... to redirect
Reference the CSS files with absolute path
and not
<link href="app/content/bootstrapwc.css" rel="stylesheet" />
Final note - doing it this way gave me full control and I did not need to do anything to the web config.
Hope this helps as this took me a while to figure out.

I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).
URL for accessing my app:
http://myapp.com/amazing_url?token=super_token
Then when the user loads the page:
http://myapp.com/amazing_url?token=super_token#/amazing_url
Then when the user navigates:
http://myapp.com/amazing_url?token=super_token#/another_url
With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.
So don't enable the HTML5 mode and then add this controller:
.config ($stateProvider)->
$stateProvider.state('home-loading', {
url: '/',
controller: 'homeController'
})
.controller 'homeController', ($state, $location)->
if window.location.pathname != '/'
$location.url(window.location.pathname+window.location.search).replace()
else
$state.go('home', {}, { location: 'replace' })

Related

Why Angular UI Router does not load my template?

I am really struggling with Angular since it is very fragile i think and I have a very simple case (probably the simplest case ever) which does not work yet.
Here is my module (so i do inject the library):
angular.module(
'module', ['ui.router']
My index.html:
<html data-ng-app="module">
<head>
... several libraries and my js files including ui-router library js + my app.js where the state definitions are located.
</head>
<body>
<div ui-view></div>
</body>
And why is not my template injected in ui-view?
EDIT: Sorry, i was in a hurry, forgot to add some details.. I have updated the app.js section like this:
.state('default',
{
url: '/',
template: '<h1>default</h1>'
})
.state('x',
{
url: '/x',
template: '<h1>X</h1>'
});
Now default state works as expected. But i call the url "host/x" i get a "Cannot GET /x".. when i call the url like "host/#x", it works.
But i have also this section for html5 mode in my app.js:
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
I have also this in the head section of my index.html:
<base href="/">
I thought, html5 should already handle the hash(#) part of the url? How can i get rid of that # in URL, so i can call directly "host/x"?
You need to specify the url property and go to this url to see this page. State should be something like:
.state("yourStateName", {
template: "<h1>My Contacts</h1>",
url: "/stateURL"
})
This is working example of url provider form my project:
angular.module("app")
.config(function ($urlRouterProvider, $locationProvider, $stateProvider) {
$locationProvider
.html5Mode(true);
$urlRouterProvider.when('/', '/url1');
$urlRouterProvider.when('', '/url2');
$urlRouterProvider.when('/url3', 'url4');
$urlRouterProvider.otherwise('/url5');
});

Angularjs base tag and $locationProvider prevents templates to be loaded

I want to remove the # on angularjs url. So I followed this blog.
This is my .config() :
.config(['$stateProvider', '$locationProvider' function($stateProvider, $locationProvider,) {
$stateProvider.state('main', {
url: '/',
templateUrl: 'path/to/main.html',
controller:'mainCtrl'
})
$locationProvider.html5Mode(true);
}])
And this is my <header> :
<head>
<scripts>....
<base href="/"> // I ADDED THIS
</head>
But when I access the / link. Like this http://localhost/my-app/ it only shows a blank page. There are no error/s on the console so Im assuming that the problem is on the loading of the template. Im using ui.router. Someone encountered this problem? Thanks.
1st
When you use <base href="/"> yu set ALL relative URLs appends to that path.
So IF your app is aviable at /my-app/ use <base href="/my-app/">
Also you can try relative base href <base href="./">, but i don't recomend it.
Now your app is in http://localhost/my-app/ but base is http://localhost/
2nd
When you use html5 routing, you may ensure that webserver does not repsonse other page, but your index.html
3rd, after that check your JS, maybe cant load template because of base url...

Angular UI-Router Not Resolving with Internet Explorer 9

I have an Angular v1.3 application, which uses Angular ui-router v0.2.13 for all routing. The site works great on all browsers, including IE 10 and IE 11, but not IE 9 (we've decided not to pursue IE8, which I understand isn't supported by v1.3, anyway). Despite my best efforts, IE 9 continually resolves to my $stateProvider's otherwise route (which is set to /*path, a possible culprit, so I disabled that route for testing purposes).
In an attempt to get any other route to resolve, I've tried setting $locationProvider.html5Mode(false), modified the $locationProvider.hashPrefix, changed the <base href="/" /> to various URLs, including <base href="/#!"/>, and I've even included xmlns:ng="http://angularjs.org" in the <html> tag for good measure. No matter what I try, IE 9 continually tries to resolve to my otherwise route, or nothing if that route is disabled. BTW, my home page route URL is set to /.
I've been up to my eyeballs in code with a launch deadline looming, so I'll be the first to admit that I'm potentially overlooking something obvious. Can anyone offer any other tips or tricks to cause ui-router to resolve properly in IE 9?
We use something like the following:
<!DOCTYPE html>
<html lang="fr" xmlns="http://www.w3.org/1999/xhtml" ng-csp xml:lang="fr-CA">
//...
var app = angular.module('YourApp', [...]);
angular.bootstrap(document, ['YourApp'], {strictDi: true})
//...
angular.module('YourApp').config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix('!');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
cache: false,
controller: 'HomeController as vm'
})
.state('anon', {
url: '/info',
controller: 'AnonController as vm'
})
//etc...
For me, IE9 routes correctly for hash urls, /#/example, but visiting / would resolve to the otherwise route. I worked around this by using a function for otherwise, and checking the url in it.
$urlRouterProvider.otherwise(function($injector){
var state = $injector.get('$state');
var location = $injector.get('$location');
if (!location.url()) {
// handle HTML5 fallback / IE9 when url has no hash
return state.go('home');
}
state.go('404');
});

Routing single page application using angular js

I am building a web Single Page Application using AngularJS. I need that clicking on link change URI in client browser without http request.
http://example.com/ ---> it shows my single page application and clicking on a specific link I need the URL is http://example.com/about but without send http request and show hidden div.
I don't know what you precisely want to do but if you only want do one http request you can perhaps use angular ui router with something like
$stateProvider
.state('main', {
url: "/",
templateUrl: "main.html"
})
.state('about', {
url: "/about",
templateUrl: "main.html",
controller: function($scope) {
$scope.showDiv = "true";
}
})
That way you can switch state and because everything you need is already loaded, nothing gets loaded anymore. Or perhaps you can also use parameters.
But why is it so bad to have one additional request? That would be something interesting to know! :)
EDIT: The easy approach with $location
(https://docs.angularjs.org/guide/$location)
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<base href="/">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="html5-mode">
<div ng-controller="LocationController">
<button ng-click="changeUrl()">Change url</button>
</div>
</body>
</html>
app.js:
angular.module('html5-mode', [])
.controller("LocationController", function ($scope, $location) {
$scope.$location = {};
$scope.changeUrl = function () {
// https://docs.angularjs.org/guide/$location
console.log("The current path: " + $location.path());
console.log("Changing url...");
$location.path('/newValue')
};
})
.config(function ($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
})
Be sure to set the basePath correct.
Take a look at html2js. This is a grunt task to convert your html templates into a pre-cached js file.
Ideally you would run this as part of your build process. As well you can run a watch task to compile your HTML templates into the pre-cache whenever you save a template -- this is nice for development.
If you are already using gulp, there is a package for you. There are many alternatives to html2js that do essentially the same thing. So if it doesn't suit your needs, try another.
So with this in place, when you navigate to another page -- the HTML template will just be pulled out of angular's cache, and not grabbed from the server.

Reading query string data from requested url in angularJs [duplicate]

I'd like to read the values of URL query parameters using AngularJS. I'm accessing the HTML with the following URL:
http://127.0.0.1:8080/test.html?target=bob
As expected, location.search is "?target=bob".
For accessing the value of target, I've found various examples listed on the web, but none of them work in AngularJS 1.0.0rc10. In particular, the following are all undefined:
$location.search.target
$location.search['target']
$location.search()['target']
Anyone know what will work? (I'm using $location as a parameter to my controller)
Update:
I've posted a solution below, but I'm not entirely satisfied with it.
The documentation at Developer Guide: Angular Services: Using $location states the following about $location:
When should I use $location?
Any time your application needs to react to a change in the current
URL or if you want to change the current URL in the browser.
For my scenario, my page will be opened from an external webpage with a query parameter, so I'm not "reacting to a change in the current URL" per se. So maybe $location isn't the right tool for the job (for the ugly details, see my answer below). I've therefore changed the title of this question from "How to read query parameters in AngularJS using $location?" to "What's the most concise way to read query parameters in AngularJS?". Obviously I could just use javascript and regular expression to parse location.search, but going that low-level for something so basic really offends my programmer sensibilities.
So: is there a better way to use $location than I do in my answer, or is there a concise alternate?
You can inject $routeParams (requires ngRoute) into your controller. Here's an example from the docs:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
EDIT: You can also get and set query parameters with the $location service (available in ng), particularly its search method: $location.search().
$routeParams are less useful after the controller's initial load; $location.search() can be called anytime.
Good that you've managed to get it working with the html5 mode but it is also possible to make it work in the hashbang mode.
You could simply use:
$location.search().target
to get access to the 'target' search param.
For the reference, here is the working jsFiddle: http://web.archive.org/web/20130317065234/http://jsfiddle.net/PHnLb/7/
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $location) {
$scope.location = $location;
$scope.$watch('location.search()', function() {
$scope.target = ($location.search()).target;
}, true);
$scope.changeTarget = function(name) {
$location.search('target', name);
}
}
<div ng-controller="MyCtrl">
Bob
Paul
<hr/>
URL 'target' param getter: {{target}}<br>
Full url: {{location.absUrl()}}
<hr/>
<button ng-click="changeTarget('Pawel')">target=Pawel</button>
</div>
To give a partial answer my own question, here is a working sample for HTML5 browsers:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<script>
angular.module('myApp', [], function($locationProvider) {
$locationProvider.html5Mode(true);
});
function QueryCntl($scope, $location) {
$scope.target = $location.search()['target'];
}
</script>
</head>
<body ng-controller="QueryCntl">
Target: {{target}}<br/>
</body>
</html>
The key was to call $locationProvider.html5Mode(true); as done above. It now works when opening http://127.0.0.1:8080/test.html?target=bob. I'm not happy about the fact that it won't work in older browsers, but I might use this approach anyway.
An alternative that would work with older browsers would be to drop the html5mode(true) call and use the following address with hash+slash instead:
http://127.0.0.1:8080/test.html#/?target=bob
The relevant documentation is at Developer Guide: Angular Services: Using $location (strange that my google search didn't find this...).
It can be done by two ways:
Using $routeParams
Best and recommended solution is to use $routeParams into your controller.
It Requires the ngRoute module to be installed.
function MyController($scope, $routeParams) {
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
// $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
var search = $routeParams.search;
}
Using $location.search().
There is a caveat here. It will work only with HTML5 mode. By default, it does not work for the URL which does not have hash(#) in it http://localhost/test?param1=abc&param2=def
You can make it work by adding #/ in the URL. http://localhost/test#/?param1=abc&param2=def
$location.search() to return an object like:
{
param1: 'abc',
param2: 'def'
}
$location.search() will work only with HTML5 mode turned on and only on supporting browser.
This will work always:
$window.location.search
Just to summerize .
If your app is being loaded from external links then angular wont detect this as a URL change so $loaction.search() would give you an empty object . To solve this you need to set following in your app config(app.js)
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider)
{
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
Just a precision to Ellis Whitehead's answer. $locationProvider.html5Mode(true); won't work with new version of angularjs without specifying the base URL for the application with a <base href=""> tag or setting the parameter requireBase to false
From the doc :
If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
you could also use $location.$$search.yourparameter
I found that for an SPA HTML5Mode causes lots of 404 error problems, and it is not necessary to make $location.search work in this case. In my case I want to capture a URL query string parameter when a user comes to my site, regardless of which "page" they initially link to, AND be able to send them to that page once they log in. So I just capture all that stuff in app.run
$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
if (fromState.name === "") {
e.preventDefault();
$rootScope.initialPage = toState.name;
$rootScope.initialParams = toParams;
return;
}
if ($location.search().hasOwnProperty('role')) {
$rootScope.roleParameter = $location.search()['role'];
}
...
}
then later after login I can say
$state.go($rootScope.initialPage, $rootScope.initialParams)
It's a bit late, but I think your problem was your URL. If instead of
http://127.0.0.1:8080/test.html?target=bob
you had
http://127.0.0.1:8080/test.html#/?target=bob
I'm pretty sure it would have worked. Angular is really picky about its #/

Resources