angularjs - 使用 AnugularJS 输出 JSON-LD 以进行结构化数据标记

标签 angularjs json rich-snippets json-ld structured-data

我一直在网上搜索一种使用 AngularJS 创建和输出 JSON-LD 对象的方法,但没有成功。

我想要实现的是将结构化数据添加到我的 SPA 中,如此处事件所述:

<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "Event",
  "name": "Example Band goes to San Francisco",
  "startDate" : "2013-09-14T21:30",
  "url" : "http://example.com/tourdates.html",
  "location" : {
    "@type" : "Place",
    "sameAs" : "http://www.hi-dive.com",
    "name" : "The Hi-Dive",
    "address" : "7 S. Broadway, Denver, CO 80209"
  }
}
</script>

https://developers.google.com/structured-data/rich-snippets/events

一种简单的方法是构建 JSON-LD 对象并将其输出到脚本标记内。但据我所知,在这样的脚本标签中访问范围值是不可能的/好的做法:
<script type="application/ld+json">
{{jsonLdObject}} 
</script>

任何人都可以用更好的方法来帮助我做到这一点,是否可以将 JSON-LD 对象创建为通常的 JSON 对象?

最佳答案

我最终使用了 Tjaart 建议的这个解决方案:
https://stackoverflow.com/a/35333500/3502352

HTML:

<div ng-controller="TestController">
  <jsonld data-json="jsonId"></jsonld>
</div>

Javascript:
var myApp = angular.module('application', []);

myApp.controller('TestController', ['$scope', function($scope) {
  $scope.jsonId = {
    "@context": "http://schema.org",
    "@type": "Place",
    "geo": {
      "@type": "GeoCoordinates",
      "latitude": "40.75",
      "longitude": "73.98"
    },
    "name": "Empire State Building"
  };
}]).directive('jsonld', ['$filter', '$sce', function($filter, $sce) {
  return {
    restrict: 'E',
    template: function() {
      return '<script type="application/ld+json" ng-bind-html="onGetJson()"></script>';
    },
    scope: {
      json: '=json'
    },
    link: function(scope, element, attrs) {
      scope.onGetJson = function() {
        return $sce.trustAsHtml($filter('json')(scope.json));
      }
    },
    replace: true
  };
}]);

关于angularjs - 使用 AnugularJS 输出 JSON-LD 以进行结构化数据标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34629273/

相关文章:

html - 在丰富的代码段中为 Itemscope 属性分配一个值

javascript - 在 1.5 中访问组件 $scope inside 指令

javascript - 如何使用 Angular-Translate 显示翻译?

javascript - 如何在页面加载时仅显示一次 Angular 引导模式?

jquery - 有没有办法在 jqgrid treeGrid url 请求中传回附加数据?

javascript - 如何从 Angular 读取 Node 服务器的json响应

schema.org - 可以用结构化数据审查一个人吗?

javascript - 我可以发回函数引用作为对 api 请求的响应吗?

arrays - 解析 JSON 来做数学题?

microdata - schema.org - 将视频对象嵌套在产品中