How to make clickable URL's in JSON response f

2019-06-06 23:54发布

问题:

I have an AngularJS, JS, JQ, HTML5 web app, which can send different http methods to project's RESTful Web Service and receive responses from it. Response comes in JSON and looks like this:

This is displayed in a <pre> element this way:

<div ng-controller="responseController">
    <span class="status-{{response.status}}">{{response.code}} {{response.description}}</span>
    <pre>{{response.data}}</pre>
    <p id="responseHeaders">Response headers:</p>
    <table>
        <tr  ng-repeat="header in response.headers">
            <td><a href="#" ng-click="addToHeaders(header)">{{header.name}}</a></td>
            <td><span>{{header.value}}</span></td>
        </tr>
    </table>
</div>

What I want is to have all the URL's that are received in JSON clickable, so I could hang a ng-click on them and go on with next steps. But I can't do it in a <pre> element.

Any ideas how this can be solved? Every useful answer is highly appreciated and evaluated.

Thank you.

回答1:

You can achieve this using a directive (here's an example):

.directive('jsonLink', function() {
    var hrefLinks=function (obj, pretty) {
      var space = pretty || '';
      var html = '';
      $.each(obj, function(key, val) {
        if ($.isPlainObject(val)) {
          html += key + ': <br>';
          html += hrefLinks(val, space + '&nbsp;&nbsp;');
        } else if (key === 'href') {
          html += space + 'LINK: <a href="' + val + '">' + val + '</a><br>';
        } else {
          html += space + key + ': ' + val + '<br>';
        }
      });
      return html;
    }
    return {
      restrict: 'E',
      template: '<div></div>',
      replace: true,
      scope: {
        obj: '='
      },
      link: function(scope, element, attr) {
        element.html(hrefLinks(scope.obj));
      }
    };
  })

Then drop this in your HTML

<json-link obj="objWithLinks"></json-link>


回答2:

You will need to replace all URLs within the response body with links.

Take a look at this answer. You have some libraries there that will solve your problem.

Autolinker.js seems like a good choice.