AngularJS脚本标记JSON-LD脚本、标记、AngularJS、JSON

由网友(迷途)分享简介:你如何创建一个应用程序/ LD + JSON 剧本标记在AngularJS动态内置JSON对象。 How do you create an application/ld+json script tag with a dynamically built JSON object in AngularJS .这是我需要...

你如何创建一个应用程序/ LD + JSON 剧本标记在AngularJS动态内置JSON对象。

How do you create an application/ld+json script tag with a dynamically built JSON object in AngularJS .

这是我需要的脚本标记看起来像

This is what I need the script tag to look like

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

我曾尝试以下code,但我不能得到它的工作:

I have tried the following code but I cant get it to work:

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标签内的前pression不会执行。脚本标记之外的前pression正确执行,并显示JSON

The expression inside the script tag does not execute. The expression outside the script tag executes correctly and displays the JSON

请参见的jsfiddle

推荐答案

咖啡我想起了世界杯之后有一个 trustAsHtml 功能。

After a cup of coffee I remembered there is a $sce service with a trustAsHtml function.

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

I created a directive that accepts a json parameter for easy re-use

请参阅更新和工作code如下:

Please see updated and working code below:

HTML

<div ng-controller="TestController">
  <jsonld data-json="jsonId"></jsonld>
</div>

的JavaScript

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

阅读全文

相关推荐

最新文章