我尝试将JSON内容转换为表格格式的逗号分隔值。
我使用table
和ng-repeat
来实现这一点,但我在每个值的末尾都有一个额外的空格。
HTML code:
<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 看起来像,[确切代码在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
之后{I} ,
,我得到了空间。
我不需要那个。我该如何删除/修剪它?
我尝试了<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
答案 0 :(得分:2)
HTML中的换行符计为空格。只需将跨度链接在一起,它们之间没有空格
<span ng-repeat="type in resultValues | filter: {typeName: types.typeName}"><span ng-bind="type.values"></span><span ng-show="!$last">, </span></span>
http://plnkr.co/edit/ybTEO8AvgU3XaN7tsRqT?p=preview
或者,您可以使用this answer并完全避免ngRepeat