2016-01-06 51 views
3

我一直在網上尋找一種方法來創建和輸出帶有AngularJS的JSON-LD對象,但沒有運氣。用AnugularJS輸出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對象?

+2

的可能的複製[AngularJS腳本標記JSON-LD(HTTP ://stackoverflow.com/questions/35332430/angularjs-script-tag-json-ld) –

回答

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 
    }; 
}]);