我使用AngularJS 1.4.8中的this solution在script
部分的body
标记中生成JSON-LD。该指令定义为
myApp.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
};
}]);
jsonId
在控制器中定义
myApp.controller('MyWorkCtrl',['$scope', '$routeParams', '$http', function($scope, $routeParams, $http){
$http.get('/works/' + $routeParams.workId + '.json').success(function(data) {
$scope.work = data;
$scope.jsonId = {
"@context": "http://schema.org",
"@type": "Book",
"creator": data['authors'],
"name": data['title'],
"isbn": data['isbn'],
"bookFormat": data['page_size'],
"numberOfPages": data['pages'],
"translator": data['translators'],
"image": data['image']
};
});
}]);
然后只是放置指令
<jsonld data-json="jsonId"></jsonld>
除了在script
中生成带有Json-LD的body
标记之外,它工作正常。如何将其移至head
部分,如Google建议的那样?