我使用的模式来自 ngBoilerplate 项目。在这种模式中,有一个整体应用程序控制器处理“全局”范围,包括元标记。
当导航到各个页面的控制器时,它们可能会发出一个事件,$locationChangeSuccess
如果您使用的是默认路由器。
应用程序控制器侦听此事件,并使用它来更新 ngBoilerplate 情况下的页面标题:https://github.com/ngbp/ngbp/blob/v0.3.2-release/src/app/app.js#L17-L21 https://github.com/ngbp/ngbp/blob/v0.3.2-release/src/app/app.js#L17-L21
但是,没有什么可以阻止您发出带有您喜欢的任何元标记信息的对象,然后为该事件提供侦听器。
// on your individual app pages goes something like this
function SomePageController($scope) {
// the event gets fired when the page is loaded and the controller is called.
$scope.$emit('newPageLoaded', { 'title': 'Some Page', 'description': 'blah' });
}
// your overall app controller
function AppController($scope) {
$scope.metadata = {
'title': 'default title',
'description': 'default description',
};
// whenever a controller emits the newPageLoaded event, we update the app's metadata
$scope.$on('newPageLoaded', function(event, metadata) {
$scope.metadata = metadata
});
}
然后在你的标题中你可以做这样的事情:
<html ng-app="myApp" ng-controller="AppController">
<head>
<meta title="{{ metadata.title }}" ng-if="metadata.title" />
<meta description="{{ metadata.description}}" ng-if="metadata.description" />
<meta whatever="{{ metadata.whatever}}" ng-if="metadata.whatever" />
</head>
我还没有测试过这段代码,所以可能会有错误,但我认为总体原则是合理的。
注释:社交媒体共享
在您的问题中,您提到了合并标签以进行社交媒体共享的用例。我假设你的意思是开放图或推特等。
在这种情况下,重要的是要知道当前这些网站(facebook、twitter、pinterest 等)使用的爬虫将not执行您的 JavaScript,因此将无法读取您用 Angularjs 动态填充的任何元标记。
我写了一篇关于这个问题的博客文章,并提供了建议的解决方案:http://www.michaelbromley.co.uk/blog/171/enable-rich-social-sharing-in-your-angularjs-app/ http://www.michaelbromley.co.uk/blog/171/enable-rich-social-sharing-in-your-angularjs-app/