angular.js - 单页应用的页面title大家都是怎么处理的
漂亮男人
漂亮男人 2017-05-15 16:57:53
0
3
586

现在越来越多的网站都在使用spa技术,前端自己路由,局部刷新页面,来实现的单页应用也就webapp,相比较之前的整站都是独立的页面,每个页面都有单独的html来写上<title>你是猴子派来的逗比么</title>,那单页应用大家是怎么处理页面title问题的了

漂亮男人
漂亮男人

reply all(3)
曾经蜡笔没有小新

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.

習慣沉默
<title>{{mainAppCtrl.title}}</title>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template