簡體   English   中英

AngularJS腳本標記JSON-LD

[英]AngularJS script tag JSON-LD

如何在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>

調節器

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

腳本標記內的表達式不會執行。 腳本標記外部的表達式正確執行並顯示JSON

請看jsfiddle

trustAsHtml一杯咖啡后,我記得有一個帶有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

在此輸入圖像描述

Tjaart van der Walt的答案在Google測試工具中對我不起作用。 它確實與真正的爬蟲一起工作。 所以我找到了另一個“老派”解決方案,它可以解決問題:

HTML

<script type="application/ld+json" id="json-ld-music-group"></script>

var schemaOrg = angular.toJson({
    '@context': 'http://schema.org',
    '@type': 'MusicGroup',
    ...
});

angular.element(document).ready(function() {
    var jsonLd = angular.element(document.getElementById('json-ld-music-group'))[0];
    jsonLd.innerHTML = schemaOrg;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM