gpt4 book ai didi

javascript - AngularJS 脚本标签 JSON-LD

转载 作者:可可西里 更新时间:2023-11-01 01:18:00 24 4
gpt4 key购买 nike

如何在 AngularJS 中使用动态构建的 JSON 对象创建 application/ld+json script 标签。

这就是我需要的脚本标签的样子

<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>

Controller

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 标签内的表达式不执行。脚本标签外的表达式正确执行并显示JSON

请参阅jsfiddle

最佳答案

喝了一杯咖啡后,我想起了一个带有 trustAsHtml 函数的 $sce 服务。

我创建了一个接受 json 参数的指令,以便于重复使用

请查看下面的更新和工作代码:

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

这是脚本输出的图像

请查看更新的jsfiddle

enter image description here

关于javascript - AngularJS 脚本标签 JSON-LD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35332430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com