Using HTML5 pushstate on angular.js

JavascriptAngularjs

Javascript Problem Overview


I am trying to implement html5's pushstate instead of the # navigation used by Angularjs. I have tried searching google for an answer and also tried the angular irc chat room with no luck yet.

This is my controllers.js:

function PhoneListCtrl($scope, $http) {
	$http.get('phones/phones.json').success(function(data) {
		$scope.phones = data;
	});
}

function PhoneDetailCtrl($scope, $routeParams) {
  $scope.phoneId = $routeParams.phoneId;
}

function greetCntr($scope, $window) {
	$scope.greet = function() {
	$("#modal").slideDown();
	}
}

app.js

angular.module('phoneapp', []).
	config(['$routeProvider', function($routeProvider){
		$routeProvider.
			when('/phones', {
				templateUrl: 'partials/phone-list.html',
				controller: PhoneListCtrl
			}).
			when('/phones/:phoneId', {
				templateUrl: 'partials/phone-detail.html',
				controller: PhoneDetailCtrl
			}).
			otherwise({
				redirectTo: '/phones'
			});
	}])

Javascript Solutions


Solution 1 - Javascript

Inject $locationProvider into your config, and set $locationProvider.html5Mode(true).

http://docs.angularjs.org/api/ng.$locationProvider

Simple example:

JS:

myApp.config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
    .when('/page1', { template: 'page1.html', controller: 'Page1Ctrl' })
    .when('/page2', { template: 'page2.html', controller: 'Page2Ctrl' })
});

HTML:

<a href="/page1">Page 1</a> | <a href="/page2">Page 2</a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhilarlView Question on Stackoverflow
Solution 1 - JavascriptAndrew JoslinView Answer on Stackoverflow