Tja*_*alt 17 javascript json angularjs json-ld
如何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>
Run Code Online (Sandbox Code Playgroud)
我尝试了以下代码,但我无法让它工作:
HTML
<div ng-controller="TestController">
<script type="application/ld+json">
{{jsonId|json}}
</script>
{{jsonId|json}}
</div>
Run Code Online (Sandbox Code Playgroud)
调节器
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"
};
}]);
Run Code Online (Sandbox Code Playgroud)
脚本标记内的表达式不会执行.脚本标记外部的表达式正确执行并显示JSON
请看jsfiddle
Tja*_*alt 18
喝完一杯咖啡后,我记得有$sce
一项trustAsHtml
功能服务.
我创建了一个接受json
参数的指令,以便于重复使用
请参阅以下更新和工作代码:
HTML
<div ng-controller="TestController">
<jsonld data-json="jsonId"></jsonld>
</div>
Run Code Online (Sandbox Code Playgroud)
使用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
};
}]);
Run Code Online (Sandbox Code Playgroud)
这是脚本输出的图像
请参阅更新的jsfiddle
归档时间: |
|
查看次数: |
3950 次 |
最近记录: |