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

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

问题描述

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

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

我已经尝试了以下代码,但我无法让它工作:

HTML

<脚本类型=应用程序/ld+json">{{jsonId|json}}{{jsonId|json}}

控制器

var myApp = angular.module('application', []);myApp.controller('TestController', ['$scope', function($scope) {$scope.jsonId = {"@context": "http://schema.org","@type": "地点",地理":{"@type": "地理坐标","纬度": "40.75",经度":73.98"},"name": "帝国大厦"};}]);

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

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>

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

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

Please see jsfiddle

解决方案

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

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

Please see updated and working code below:

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

Here is a image of the script output

Please see updated jsfiddle

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

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