通过对象的 ng-repeat 循环行为不正常
ng-repeat loop through object is not behaving properly
在我的 Angularjs 中 ng-repeat 只跟随一个对象,字段减少了实际上我在这个对象中有超过 40 个。如果我有 40 个字段,那么将渲染 40 个空输出(见下面的输出)。
{"Name": "Raj", "Gender":"M", "Country": "India"} (ONLY ONE OBJECT)
Angular 查看
<table ng-repeat="emp in model.Employee">
<tr>
<td><strong>Name:</strong></td>
<td>{{emp.Name}}</td>
</tr>
<tr>
<td><strong>Gender:</strong></td>
<td>{{emp.Gender}}</td>
</tr>
</table>
异常输出为
Name: Raj
Gender: M
但实际输出是渲染了三次没有价值。
Name:
Gender:
Name:
Gender:
Name:
Gender:
发生这种情况是因为您正在遍历对象而不是数组。因此,ngRepeat
循环将 运行 与对象中的键一样多。因为对象中有三个键,所以循环 运行 三次。此外,emp
(可迭代对象)是键('Name'、'Gender'、'Country')而不是完整的对象。
更改为:
[{"Name": "Raj", "Gender":"M", "Country": "India"}]
您可以为此目的使用 (key,value)。
var app = angular.module("app",[])
app.controller('ctrl',['$scope', function($scope){
$scope.data ={"Name": "Raj", "Gender":"M", "Country": "India"};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="item item-checkbox">
<table >
<tr ng-repeat="(key,value) in data" ng-if="key != 'Country'">
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
</table>
</div>
在我的 Angularjs 中 ng-repeat 只跟随一个对象,字段减少了实际上我在这个对象中有超过 40 个。如果我有 40 个字段,那么将渲染 40 个空输出(见下面的输出)。
{"Name": "Raj", "Gender":"M", "Country": "India"} (ONLY ONE OBJECT)
Angular 查看
<table ng-repeat="emp in model.Employee">
<tr>
<td><strong>Name:</strong></td>
<td>{{emp.Name}}</td>
</tr>
<tr>
<td><strong>Gender:</strong></td>
<td>{{emp.Gender}}</td>
</tr>
</table>
异常输出为
Name: Raj
Gender: M
但实际输出是渲染了三次没有价值。
Name:
Gender:
Name:
Gender:
Name:
Gender:
发生这种情况是因为您正在遍历对象而不是数组。因此,ngRepeat
循环将 运行 与对象中的键一样多。因为对象中有三个键,所以循环 运行 三次。此外,emp
(可迭代对象)是键('Name'、'Gender'、'Country')而不是完整的对象。
更改为:
[{"Name": "Raj", "Gender":"M", "Country": "India"}]
您可以为此目的使用 (key,value)。
var app = angular.module("app",[])
app.controller('ctrl',['$scope', function($scope){
$scope.data ={"Name": "Raj", "Gender":"M", "Country": "India"};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="item item-checkbox">
<table >
<tr ng-repeat="(key,value) in data" ng-if="key != 'Country'">
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
</table>
</div>