【问题标题】:Convert JSON Array to HTML wrapped String - Angular Service将 JSON 数组转换为 HTML 包装的字符串 - Angular 服务
【发布时间】:2014-04-30 17:09:03
【问题描述】:

我正在尝试在我的 Angular 应用程序中使用所见即所得。我想要发生的是,我查询一个对象数组的端点。然后根据属性名称,其中的数据被包装到不同的 html 标记中。然后将所有数据连接成一个字符串,该字符串在我的应用程序中以所见即所得的方式显示。

所以 JSON 看起来像

[   
    {
    "name": "steve",
    "age": 33,
    "profile": "http://www.profile.com/steve",
    "location": "New York"
    },{
    "name": "john",
    "age": 25,
    "profile": "http://www.profile.com/john",
    "location": "LA"
    },
]

吐出:

"<b>Steve - New York</b>
<br>
<a href='http://www.profile.com/steve'>Url</a>
<br>
<span>33</span>
<br>
<br>

<b>John - LA</b>
<br>
<a href='http://www.profile.com/john'>Url</a>
<br>
<span>25</span>
<br>
<br>"

虽然这部分不是 Angular 特定的。我想我需要将此代码添加到服务中,以便在我需要它作为应用程序时可以重用它。

我不确定这段代码会是什么样子。有什么想法吗?

编辑:为了澄清我这样做的原因是因为页面上有一个所见即所得。非技术用户需要能够在所见即所得中编辑数据,然后单击按钮,应用程序将导出 PDF。 WYSIWYG 需要带有 HTML 标记的单个字符串,生成 PDF 文件的应用程序后端也是如此。

【问题讨论】:

  • 如果您使用 AngularJS,生成 HTML 可能不是您最好的选择:您最好使用 Angular 的 MVC 工具根据您的数据自动更新视图。
  • 是的,但它在所见即所得,因此非技术用户可以编辑文本,然后单击一个按钮,它会为他们吐出一个 PDF。所见即所得需要一个包含 HTML 的字符串。

标签: javascript json angularjs wysiwyg


【解决方案1】:

在我看来,真的没有理由在这里重新发明轮子......为什么不能只使用像 TinyMCE 这样的完全支持的所见即所得编辑器?它通过这里的 Angular-UI 项目进行了角度扩展:

https://github.com/angular-ui/ui-tinymce

然后你可以在你的html中写这个:

<textarea ui-tinymce="tinyMceOptions" ng-model="parsedResponse"></textarea>
<button ng-click="convertToPdf()">Y U NO DOWNLOAD PDF?</button>

在您的控制器(或指令)中:

$scope.tinyMceOptions = {/*Customize here*/};

$scope.parseMyResponse = function(data) {
  // do something with data and return as html string
  return data;
};

$http.get('/your/resource/url').success(function(result) {
  $scope.parsedResponse = $scope.parseMyResponse(result);
});

$scope.convertToPdf = function() {
  // do something with $scope.parsedResponse here to get a PDF
};

编辑: 我想我一开始没明白你在问什么?如果你想在服务中使用它,你所要做的就是:

angular.module('app')
  .service('Util', function() {
    return {

      wrapInTag: function(tagName, value) {
        return '<' + tagName + '>' + value + '<' + tagName + '/>';
      },

      parseMyResource: function(response) {
        htmlString = '';
        angular.each(response, function(item) {
          htmlString += this.wrapInTag('h1', item.title);
          htmlString += this.wrapInTag('b', item.id);
          // Other manipulation...
        });
        return htmlString;
      }

    };
  });

然后在你的控制器中:

angular.module('app')
  .controller('MyCtrl', function(Util){
    // Use Util functions here...
  });

我已经为您提供了一些将 JSON 解析为 HTML 字符串的示例代码,但恐怕我无法更具体地说明如何编写它。如果你的解析函数的逻辑真的取决于你想要完成的事情以及你的数据模型是什么样的。确实没有直接的方法可以将 JSON 转换为 HTML。

【讨论】:

  • 是的,这正是我正在做的。你列出了我已经完成的部分。但是我不确定 parseMyResponse 函数会是什么样子来实现这个结果。此外,虽然它不是必需的,但我一直在进行代码重用,似乎 parseMyResponse 作为服务比在控制器中更好,所以我不会在每次需要 WYSIWYG 时复制和粘贴这个 parseMyResponse。
猜你喜欢
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 2013-03-14
  • 1970-01-01
相关资源
最近更新 更多