我正在尝试在我的角应用程序中使用wysiwyg。我想要发生的是,我查询一个对象数组的终点。然后根据属性名称将其中的数据包装到不同的html标记中。然后将所有数据连接成一个字符串,该字符串在我的应用程序中的wysiwyg上显示。
看起来像
的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特有的。我想我需要将此代码添加到服务中,以便在需要它时可以重复使用它。
我不确定这段代码会是什么样子。有什么想法吗?
编辑:为了澄清我之所以这样做是因为页面上有一个WYSIWYG。非技术用户需要能够在WYSIWYG中编辑数据,然后单击按钮,应用程序将导出PDF。 WYSIWYG需要一个带有HTML标记的字符串,生成PDF文件的应用程序的后端也是如此。答案 0 :(得分:0)
在我看来,真的没有理由在这里重新发明轮子......为什么你不能像TinyMCE一样使用完全支持的WYSIWYG编辑器?它通过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。