头部中的角度动态元标记 [英] Angular Dynamic meta tags in head

查看:23
本文介绍了头部中的角度动态元标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Angular 应用的特定页面上插入开放图元标记.

I need to insert open graph meta tags on a particular page in an angular app.

这些标签因页面上的新闻或视频而异.

These tags are different based on the news or video that the page has.

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

I tried adding a variable to the $rootscope. This variable will be populated with the meta tags when it is relevant.

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

Now here is my issue. As soon as this variable gets populated with the HTML string, they don't form a part of the head and are instead outputted to the body. I have searched for a day and could not find any viable solutions. Any help would be appreciated

推荐答案

我创建了一个 Angular 模块可用于使用 $routeProvider 路由定义动态设置元标记.

I created an Angular module that can be used to set meta tags dynamically using the $routeProvider route definitions.

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 中设置元标记

You can then set the meta tags in HTML like so

<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 注入控制器

To set the title, description and og:image dynamically, you can inject ngMeta into your controller

.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 的支持.

Support for more tags and ui-router are in the works.

这篇关于头部中的角度动态元标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆