头部的角度动态元标记

Cly*_*obo 3 meta-tags opengraph angularjs

我需要在角度应用程序中的特定页面上插入开放图形元标记.

这些标签根据页面的新闻或视频而有所不同.

我尝试在$ rootscope中添加一个变量.当变量相关时,将使用元标记填充此变量.

现在这是我的问题.只要此变量填充了HTML字符串,它们就不会形成头部的一部分而是输出到正文.我搜索了一天,找不到任何可行的解决方案.任何帮助,将不胜感激

WeN*_*igh 11

我创建了一个Angular模块,可以使用$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!'
    }
  })
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样在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}}" />
Run Code Online (Sandbox Code Playgroud)

要动态设置标题,描述和og:图像,您可以注入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');
});
Run Code Online (Sandbox Code Playgroud)

支持更多标签和ui-router正在开发中.

  • 我认为`setDescription(String value)`在当前版本中不可用,但`setTag(String tagName,String value)`可以完成这项工作. (2认同)