[英]Dynamic Page Titles using MEAN stack - Jade and Angular
在我的MEAN Stack应用程序中,我试图根据页面上加载的内容更改页面标题(在翡翠中设置)。 目前,它为SPA中的每个页面显示通用页面标题。
要设置索引的页面标题,我正在这样做
index.js
res.render('index', {
title: 'Generic Page Title'
});
然后,当我返回内容(不同的角度路线/页面)时,我想更新此标题
offer.js
Offer.find(searchObject).sort('-pricing.pctSavings').exec(function(err, offers){
if (err) {
res.render('error', {
status: 500
});
} else {
//update title?
res.jsonp(offers);
}
});
头玉
title= appName+' - '+title
我不确定如何更改此设置,因为商品在页面内作为json返回。 我尝试将标题添加到响应中(res.locals.title ='测试唯一标题'),但是它不起作用。
有任何想法吗?
谢谢!
添加更多信息:
我可以在翡翠模板中包含一些html,如下所示:
头玉
head
div(data-ng-include="'views/dynamic_title.html'")
meta(charset='utf-8')
meta(http-equiv='X-UA-Compatible', content='IE=edge,chrome=1')
meta(name='viewport', content='width=device-width,initial-scale=1,user-scalable=no')
views / dynamic_title.html
<div data-ng-controller="OffersController">
<title> Test </title> //works
<title> {{test}} </title> //test set in offers controller - doesn't work
<title> {{ Page.title() }}</title> //Page injected into offers controller - doesn't work
</div>
直到稍后才加载offers控制器...
谢谢。
我知道您不会在每次请求命中服务器时都返回玉文件。 由于SPA使用angularjs,因此您的应用程序会从服务器按需加载数据。 您必须在您的angular js代码中更改标题。
HMTL
<html ng-app="app">
<head ng-controller="TitleCtrl">
<title>{{ Page.title() }}</title>
</head>
....
</html>
JS
angular.module('app', [])
.factory('Page', function() {
var title = 'default';
return {
title: function() { return title; },
setTitle: function(newTitle) { title = newTitle }
};
})
.controller('TitleCtrl', function($scope, Page) {
$scope.Page = Page;
})
.controller('RouterPathCtrl', function($scope, Page) {
Page.setTitle('My new title')
});
每当路线改变时
Inject `Page` and Call `Page.setTitle()` from controllers.
我认为实现此目标的一种方法是将当前页面标题作为标题与响应一起发送,因此您不必将无关的信息放入JSON模型中。
res.set("title", "some title");
然后,结合请求拦截器和指令,我将读出标头并根据该标头字段更新标题标签。
module.factory("Page", function() {
return {
title: "index"
}
});
module.directive("title", ["Page",
function(Page) {
return {
restrict:"E",
link: function($scope, $element) {
$scope.$watch(function() {
return Page.title;
}, function(newValue) {
$element.html(newValue);
})
}
}
}
]);
module.factory("PageTitleInterceptor", ["Page",
function(Page) {
return {
response: function(response) {
Page.title = response.headers("title");
return response;
}
}
}
]);
看到Plunk http://plnkr.co/edit/ZNSUnqJkGXdTv9MfERYF?p=preview使用Firebug,您可以观察标题标签
问候
您可以从MEAN堆栈中的AngularJS控件内部使用javascript来更改页面标题。
只需运行
document.title = "Current Page Title";
在每个控制器的开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.