AngularJS脚本标记JSON-LD [英] AngularJS script tag JSON-LD

查看:161
本文介绍了AngularJS脚本标记JSON-LD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何创建一个应用程序/ 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

推荐答案

咖啡我想起了世界杯之后有一个 $ SCE 服务> 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

在这里输入的形象描述

这篇关于AngularJS脚本标记JSON-LD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆