More and more websites are now using SPA technology. The front-end routes itself and partially refreshes the page. The single-page application is also a webapp. Compared with the previous one, the entire site was an independent page, and each page was There is a separate html to write <title>你是猴子派來的逗比么</title>
, so how do you deal with the page title problem in single-page applications
I saw an answer on stackoverflow, he implemented it like this
First add a global controller to the html:
<html ng-app="plunker" ng-controller="MainCtrl">
Then I wrote a factory:
app.factory('Page', function(){
var title = 'default';
return {
title: function() { return title; },
setTitle: function(newTitle) { title = newTitle; }
};
});
Then index.html
主頁面中就可以通過<h1>{{ Page.title() }}</h1>
get the page title
It is very simple to set the title of the specific corresponding page, just inject this Page
into your controller
function Page2Ctrl($scope, Page) {
Page.setTitle('title1');
}
Here is the specific implementation: http://plnkr.co/edit/0e7T6l?p=info
js
中使用 document.title = '...'
就能修改 title
Got it
If you want better results, you can use the H5
的新特性 history.pushState(state, title, url)
,這個方法不但能修改 title
,還能同時修改 url
address and record this information into the history stack. When the user uses the browser's back button, they will get a better experience.