如何动态更改<title>标签?</title>

时间:2014-10-27 17:40:23

标签: javascript angularjs title

请知道如何在angularjs中动态更改内部。

我正在使用NGresource并从后端提取json数据,我想动态更改它,然后我转到一篇新文章。

4 个答案:

答案 0 :(得分:3)

您可以使用angularjs-viewhead在每个视图的基础上更改HTML标题和头元素。

这里是如何使用它。

  1. 将angularjs-viewhead.js放入资产文件夹
  2. 将您的应用程序依赖声明为正常

      

    var app = angular.module('myApp',['ng','viewhead']);

  3. 可以使用view-title指令在AngularJS应用程序中实现这种设置。首先,设置title元素以绑定到特殊范围变量viewTitle,该视图将在实例化倾斜视图时设置:

  4.    
       </title ng-bind-template="{{viewTitle}} - FooBaz">FooBaz</title>
    
    1. 有了这个,在每个视图的模板中添加一个view-title元素,设置视图的标题:
    2.    
         <view-title>About</view-title>
      

答案 1 :(得分:1)

像这样:

document.title = 'Text';

答案 2 :(得分:1)

在处理搜索引擎时更改JS中的标题很棘手,因为您可能会在搜索结果中获得花括号或页面标题不正确。但是,如果你有一个Google / Bing / Yahoo!的渲染服务器,它会在抓取时显示出来。然而,这完全是另一个问题。为此,请将ng-app指令移至html属性:

<html ng-app="myApp">
  <head>
    <title ng-bind="titleService.currentTitle">My Default Title</title>
  </head>
  <body>
    <ng-view></ng-view>
  </body>
</html>

然后创建一个服务并将其绑定到根范围:

angular.module('myApp')
  .service('TitleService', function($location) {
    var DEFAULT_TITLE = 'My Default Title';
    return {
      setTitle: function(title) {
        this.currentTitle = title || DEFAULT_TITLE;
      }
    };
  });

angular.module('myApp').run(function(TitleService, $rootScope) {
  // This is mainly for a separation of concerns. These lines could
  // easily go in the service definition.
  $rootScope.$on('$locationChangeSuccess', TitleService.setTitle);
  $rootScope.titleService = TitleService;
});

这可确保默认情况下始终设置默认标题。但是,如果您想在每个控制器/指令的基础上设置标题,您可以在代码中执行此操作:

angular.module('myApp')
  .controller('MainCtrl', function($scope, $location, TitleService, Article) {
     // I'm just guessing what your logic might look like
     var id = $location.search().articleId;
     Article.get(id).then(function(article){
        // Set the title however you want with article data
        TitleService.setTitle(article.title);
     });
  });

编辑:我将一行转移到了运行功能,以将服务的问题与应用程序的问题分开。

答案 3 :(得分:-1)

试试这个:

document.title.innerHTML = "" //Text Goes in Quotes.
祝你好运!