Deaz
Deaz

Reputation: 85

Output JSON-LD with AnugularJS for Structured Data Markup

I have been searching the web for a way to create and output a JSON-LD object with AngularJS but with no luck.

What I am trying to achieve is to add structured data to my SPA as described for events here:

<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

A simplistic way to do this could be to build the JSON-LD object and output it inside the script tag. But for my knowledge it is not possible/good practice to access scope values within a script tag like this:

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

Can anyone help me with a better approach to do this and is it okay to create the JSON-LD object as a usual JSON object?

Upvotes: 4

Views: 2646

Answers (1)

Deaz
Deaz

Reputation: 85

I ended up using this solution suggested by 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
  };
}]);

Upvotes: 3

Related Questions