【发布时间】:2015-08-25 18:02:09
【问题描述】:
我试图将 JSON 内容转换为表格格式的逗号分隔值。
我通过使用table 和ng-repeat 实现了这一点,但我在每个值的末尾都得到了一个额外的空格。
HTML 代码:
<div ng-controller="JsonConvertController">
<div>
<button class="btn btn-success" id="btnjsonConvert"
ng-click="convertJsonToServiceValues()">Convert Json</button>
</div>
<table>
<thead>
<tr>
<th style="width:100px;">Types</th>
<th style="width:300px;">Values</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="types in resultJson">
<td><span ng-bind="types.typeName"></span>
</td>
<td>
<span ng-repeat="type in resultValues | filter: {typeName: types.typeName}">
<span ng-bind="type.values"></span>
<span ng-show="!$last">,</span>
</span>
</td>
</tr>
</tbody>
</table>
</div>
控制器代码:
function JsonConvertController($scope, $http) {
$scope.displayTable = true;
$http.get('data.json').success(function(data) {
$scope.jsonContent = data;
});
$scope.convertJsonToServiceValues = function() {
$scope.resultJson = [];
$scope.resultValues = [];
angular.forEach($scope.jsonContent[0].types, function(types) {
$scope.resultJson.push({
typeName: types.name,
});
angular.forEach(types.domainTypes.codedValues, function(type) {
$scope.resultValues.push({
typeName: types.name,
values: type.name
});
});
});
};
}
示例 JSON 看起来像 [Exact code is in plunker]
[{
"version": 0.01,
"types": [{
"id": 1,
"name": "Type1",
"domainTypes": {
"type": "codedValue01",
"codedValues": [{
"name": "Type1Code1",
"code": "t1c1"
}, {
"name": "Type1Code2",
"code": "t1c2"
}, {
...
...
...
}]
}
}, {
"id": 2,
"name": "Type2",
"domainTypes": {
"type": "codedValue02",
"codedValues": [{
"name": "Type2Code1",
"code": "t2c1"
}, {
"name": "Type2Code2",
"code": "t2c2"
}, {
...
...
}]
}
}]
所以,输出如下所示:
Types Values
Type1 Type1Code1 , Type1Code2 , Type1Code3 , Type1Code4 , Type1Code5 ,
Type1Code6 , Type1Code7 , Type1Code8 , Type1Code9
Type2 Type2Code1 , Type2Code2 , Type2Code3 , Type2Code4 , Type2Code5
Type3 Type3Code1
Type4 Type4Code1 , Type4Code2 , Type4Code3 , Type4Code4 , Type4Code5
问题:每个值的末尾,我得到一个额外的空间。意思是Type1Code1 , 在1 和, 之后,我得到了空间。
我不需要那个。如何删除/修剪它?
我尝试了<span>{{type.values}}</span> 而不是<span ng-bind="type.values"></span>,但得到了相同的结果。
我手动设置trim(),如<span ng-bind="trimContent(type.values)"></span>,并在控制器中定义函数
$scope.trimContent = function (content) {
return content.trim();
};
这也不行。
因为我在 JSON 内容中没有任何额外的空间。有什么问题?
如何在每个值的末尾没有额外空格的情况下获取逗号分隔值?
为了更好的结果,我在Plunker中添加了我的代码
【问题讨论】:
-
你能显示输出的 HTML 吗?
-
问题中已经存在。在
So, the output is coming like the below:之后或者你可以在plunker中看到
标签: json angularjs angularjs-ng-repeat