Cannot change URL using history.replaceState in a snippet
I recently answered a question here: UI-router change state without changing url and wanted to embed my answer as a snippet. When UI-Router kicks in and tries to apply the URL Hash according to the routing rules, the URL cannot be modified and angular triggers another digest cycle. It then goes into an infinite loop attempting to set the URL.
The relevant error message is as follows:
Error: Failed to execute 'replaceState' on 'History': A history state object with URL 'http://stacksnippets.net/js#/home' cannot be created in a document with origin 'null'.
at Error (native)
at Browser.self.url (https://code.angularjs.org/1.2.25/angular.js:4506:30)
at https://code.angularjs.org/1.2.25/angular.js:9904:22
at Scope.$eval (https://code.angularjs.org/1.2.25/angular.js:12701:28)
at Scope.$digest (https://code.angularjs.org/1.2.25/angular.js:12513:31)
at Scope.$apply (https://code.angularjs.org/1.2.25/angular.js:12805:24)
at https://code.angularjs.org/1.2.25/angular.js:1447:15
at Object.invoke (https://code.angularjs.org/1.2.25/angular.js:3966:17)
at doBootstrap (https://code.angularjs.org/1.2.25/angular.js:1445:14)
at bootstrap (https://code.angularjs.org/1.2.25/angular.js:1459:12)
The code in Browser.self.url (angular.js:4506)
is doing the following:
window.history.replaceState(null, '', "http://stacksnippets.net/js#/home");
Snippet that fails
This is the snippet I am trying to embed (run at your own risk, it will trigger digest loops infinitely). You can see this snippet working OK at plnk.co: http://plnkr.co/edit/w2aolrt9wdW3EFcEB3Lw?p=preview
var app = angular.module('demonstrateissue', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider.state({
name: 'home',
url: '/home',
controller: function() { },
template: '<h1>Home</h1><div ui-view></div>'}
);
$stateProvider.state({
name: 'home.foo',
url: '/foo',
controller: function() { },
template: '<h1>foo</h1>'}
);
});
app.run(function($rootScope, $state, $location) {
$rootScope.$state = $state;
$rootScope.$location = $location;
// This function will go to home.foo state but not change url
$rootScope.gotofoo = function() {
$state.go("home.foo", {}, { location: false } );
};
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
<script data-require="ui-router@*" data-semver="0.2.13" src="https://rawgit.com/angular-ui/ui-router/0.2.13/release/angular-ui-router.js"></script>
</head>
<body ng-app="demonstrateissue">
<!-- click this -->
<a href ng-click="gotofoo()">Go to foo dont change url</a>
<div ui-view>/div>
<div class="header">
Current URL: <b>{{$location.url() }}</b> <br>
Current State: <b>{{$state.current.name }}</b> <br>
Current Params: <b>{{$state.params | json }}</b><br>
</div>
</body>
</html>