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

时间:2016-01-06 09:09:45

标签: 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标记内。但据我所知,在脚本标记中访问范围值是不可能的/良好做法,如下所示:

<script type="application/ld+json">
{{jsonLdObject}} 
</script>

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

1 个答案:

答案 0 :(得分:3)

我最终使用了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
  };
}]);