如何application/ld+json
script
在AngularJS中使用动态构建的JSON对象创建标签。
这就是我需要的脚本标签看起来像
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Place",
"geo": {
"@type": "GeoCoordinates",
"latitude": "40.75",
"longitude": "73.98"
},
"name": "Empire State Building"
}
</script>
我已经尝试了以下代码,但无法正常工作:
的HTML
<div ng-controller="TestController">
<script type="application/ld+json">
{{jsonId|json}}
</script>
{{jsonId|json}}
</div>
控制器
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"
};
}]);
script标签内的表达式不执行。script标签外的表达式可以正确执行并显示JSON
请参阅jsfiddle
一杯咖啡后,我记得这里$sce
有一项trustAsHtml
功能。
我创建了一个接受json
参数的指令,以便于重复使用
请在下面查看更新的工作代码:
的HTML
<div ng-controller="TestController">
<jsonld data-json="jsonId"></jsonld>
</div>
Java脚本
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
};
}]);
这是脚本输出的图像
请参阅更新的jsfiddle
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句