我创建了一个Angular module,可用于使用$routeProvider 路由定义动态设置元标记。
angular.module('YourApp','ngMeta')
.config(function ($routeProvider, ngMetaProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home-template.html',
meta: {
//Sets 'Home Page' as the title when /home is open
title: 'Home page',
description: 'This is the description of the home page!'
}
})
.when('/login', {
templateUrl: 'login-template.html',
meta: {
//Sets 'Login Page' as the title when /login is open
title: 'Login page',
description: 'Login to this wonderful website!'
}
})
});
然后您可以像这样在 HTML 中设置元标记
<title ng-bind="ngMeta.title"></title>
<!-- OR <title>{{ngMeta.title}}</title> -->
<!-- This meta tag can be set using ngMetaProvider -->
<meta property="og:type" content="{{ngMeta.ogType}}" />
<!-- Default locale is en_US -->
<meta property="og:locale" content="{{ngMeta.ogLocale}}" />
<!-- This meta tag changes based on the meta object of each route -->
<!-- or when the setDescription function is called -->
<meta name="description" content="{{ngMeta.description}}" />
要动态设置标题、描述和 og:image,您可以将ngMeta 注入到您的控制器中
.controller('DemoCtrl', function(ngMeta) {
ngMeta.setTitle('Demo page');
ngMeta.setDescription('This is the description of the demo page');
ngMeta.setOgImgUrl('http://example.com/abc.jpg');
});
对更多标签和 ui-router 的支持正在开发中。