如何使用AngularJS在REST的JSON响应中创建可点击的

如何使用AngularJS在REST的JSON响应中创建可点击的

本文介绍了如何使用AngularJS在REST的JSON响应中创建可点击的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 AngularJS JS JQ HTML5 Web应用程序,它可以向项目的 RESTful Web服务发送不同的http方法,并从中接收响应。响应来自JSON,如下所示:

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:

以这种方式显示在< pre> 元素中:

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>

我想要的是让JSON中收到的所有URL都可以点击,所以我可以挂一个 ng-click ,然后继续执行后续步骤。但我无法在< pre> 元素中执行此操作。

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.

谢谢。

推荐答案

您可以使用指令实现此目的():

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

然后将其放入HTML中

Then drop this in your HTML

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

这篇关于如何使用AngularJS在REST的JSON响应中创建可点击的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 07:05