如何动态更改<标题>标签
How can I dynamicly change the <title> tag?
我想知道如何在angularjs中动态更改内部。
我正在使用NGresource并从后端提取json数据,我想动态地更改它,然后我转到一篇新文章,例如。
您可以使用angularjs viewhead在每个视图的基础上更改HTML标题和head元素。
这里是如何使用它。
-
将angularjs-viewhead.js放在资产文件夹中
-
将应用程序的依赖项声明为正常
var app=角度模块('myApp',['ng','viewhead']);
-
这种设置可以在AngularJS应用程序中使用view title指令来实现。首先,将title元素设置为绑定到特殊作用域变量viewTitle,该变量将在实例化倾斜视图时设置:
</title ng-bind-template="{{viewTitle}} - FooBaz">FooBaz</title>
- 有了这一点,可以在每个视图的模板中添加一个单独的视图标题元素来设置视图的标题:
<view-title>About</view-title>
如此:
document.title = 'Text';
在处理搜索引擎时,在JS中更改标题很棘手,因为搜索结果中可能会出现大括号,或者页面的标题不正确。但是,如果你有一个谷歌/必应/雅虎的渲染服务器!,然后它会在爬行时立即显示出来。然而,这完全是另一个问题。为此,请将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);
});
});
EDIT:我在run函数中移动了一行,将服务的关注点与应用程序的关注点分开。
试试这个:
document.title.innerHTML = "" //Text Goes in Quotes.
祝你好运!
相关文章:
- 在<页眉>标签
- 如何将Array转换为<ul><李>以字母为标题的字母列表
- <标题>插入SVG的元素不起作用
- 图表标题来自<输入类型='text'>使用jquery
- SVG<g>标记获取其<标题>contentJS/jQuery
- 如何更改<标题>网页的
- 根据关联链接更改标题的颜色?每次点击<a>应该使关联的h2变成蓝色
- 将**标题**转换为<h1>标题</h1>在一个字符串中遍历大文本
- 如何动态更改<标题>标签
- 角度2.x变化<标题>在头脑中(在我的应用程序之外)
- 设置Wordpress<标题>来自querystring
- 如何设置<一个标题=“">用于erb
- 切换列表,h4标题被更改为默认<李>
- 如何在<标题>标签
- <br>不在工具提示的标题标记中工作
- jQuery插入外部html页面<标题>进入另一个html页面
- 添加链接标题,如果<a>标签
- Javascript:更改<h2>标题的颜色为mouseover()
- 插入<脚本>代码此处</脚本>在标题中通过正文中的JS
- & lt; a>标题和打印的标题使用javascript