我一直在网上搜索一种方法,用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
};
}]);