使用angular.js将内容加载到AJAX中时,如何更改浏览器地址栏中的URL [英] how to change the url in the browser address bar when content is loaded in AJAX with angular.js
问题描述
我正在设计一个带有angular.js的Web应用程序,该应用程序内的通信是通过AJAX进行的,这意味着当这些应用程序请求Web资源时,URL浏览器地址永远不会改变.
I am designing a web app with angular.js, the communication within the application is through AJAX, that means when the apps requests a web resources, the url browser address never change.
我的应用程序正在显示建筑物信息.初始网址为'/buildings'
,首先它将显示房间列表
my app, for example, is showing the building information. The initial url is '/buildings'
, and firstly it will show a list of rooms
'/buildings/rooma'
'/buildings/roomb'
.
每当我单击会议室网址时,该页面都会通过AJAX加载会议室信息,而不会更改浏览器地址栏中的网址
whenever I click the room url, the page will load the room info through AJAX without changing the url in the browser address bar
但是现在该要求要求我为每个网址添加书签,所以这意味着每当我单击会议室网址时,浏览器地址栏就必须同时显示会议室网址,而不是初始网址.
however now the requirement asks me to bookmark each url, so it means whenever I click a room url, the browser address bar has to show the room url as well rather than the initial url.
我该如何在angularjs中甚至在没有angularjs框架的情况下做到这一点?
How could I do it in angularjs or even without angularjs framework?
更新:
我尝试了ĽubošBeran建议的解决方案
I have tried the solution suggested by Ľuboš Beran
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
console.log('success', evt, lastRoute,$route.current);
$route.current = lastRoute;
});
但是$ route.current给了我未定义的数据.
but the $route.current gives me undefined data.
推荐答案
一个好的方法是使用URL pushstate.
A good way to do this is using url pushstate.
写一个完整的工作演示太复杂了,所以您可能要用谷歌搜索它.
It's too complex to write up a complete working demo, so you may want to google it.
这是一篇不错的文章: http://www.sitepoint.com/javascript-history-pushstate/
Here's a nice article: http://www.sitepoint.com/javascript-history-pushstate/
pushstate将更改浏览器中的URL,因此用户可以将页面添加为书签.
pushstate will change the url in the browser, so the user can bookmark the page.
您还需要收听popstate:
You also need to listen for popstate:
window.addEventListener("popstate", function(e) { console.log(arguments) })
因此您可以在用户按下后退/前进按钮时做出反应.
so you can react when the user push back/forward buttons.
这篇关于使用angular.js将内容加载到AJAX中时,如何更改浏览器地址栏中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!