我一直在网上搜索一种使用 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/