给定一个对象数组的json,如何动态地使用ng-repeat显示它? error
键是静态的/始终保持不变。只是error
的值发生了变化。因此,如果我将密码字段设置为错误,那么我会在password
error
密钥
{
"error": {
"firstName": {
"0": "The first name field is required.",
"1": "The first name field must have 2-5 characters."
},
"lastName": {
"0": "The last name field is required."
}
}
}
{
"error": {
"password": {
"0": "The password field is required."
}
}
}
我尝试过:
<ul ng-repeat="message in errormessage">
<li ng-repeat="(k,v) in message">
{{k}} - {{v}}
</li>
</ul>
但它显示了这一点:
0 - [
0 - ]
答案 0 :(得分:2)
angular.module('app', [])
.controller('SampleCtrl', function($scope) {
$scope.errormessage = {
"error": {
"firstName": {
"0": "The first name field is required.",
"1": "The first name field must have 2-5 characters."
},
"lastName": {
"0": "The last name field is required."
},
"passowrd": {
"0": "The password field is required."
}
}
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="SampleCtrl">
<ul ng-repeat="message in errormessage">
<li ng-repeat="(k,v) in message">
<b>{{k}}:</b><br>
<ul>
<li ng-repeat="err in v">
{{err}}
</li>
</ul>
</li>
</ul>
</div>
&#13;
答案 1 :(得分:0)
修改强>
我认为你要考虑的第一件事是如果你控制了你的json并将其表示为这样
$scope.errormessage = {
"error": {
"firstName": {
"0": "The first name field is required.",
"1": "The first name field must have 2-5 characters."
},
"lastName": {
"0": "The last name field is required."
},
"passowrd": {
"0": "The password field is required."
},
"mail": {
"0": "The first name field is required.",
"1": "The first name field must have 2-5 characters."
},
"newsletter": {
"0": "The newsletter field is required."
},
"address": {
"0": "The address field is required."
}
}
}
为什么这样,因为你不能在同一个对象或数组上有两个字段命名错误。在此之后,提供的第一个解决方案必须正常工作
<div ng-app="app" ng-controller="SampleCtrl">
<ul ng-repeat="message in errormessage">
<li ng-repeat="(k,v) in message">
<b>{{k}}:</b><br>
<ul>
<li ng-repeat="err in v">
{{err}}
</li>
</ul>
</li>
</ul>
</div>
答案 2 :(得分:0)
确保在正确的物体上使用ng-repeat。你有:
ng-repeat="message in errormessage"
,errormessage
的内容似乎是"[]"
。见http://jsfiddle.net/hgk6vsqv/
答案 3 :(得分:0)
一些观察结果:
Given a json of array of objects
即可。您的JSON
不是array of Objects
。ng-repeat="message in errormessage.error"
代替ng-repeat="message in errormessage"
<强>样本强>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
$scope.errormessage = {
"error": {
"firstName": {
"0": "The first name field is required.",
"1": "The first name field must have 2-5 characters."
},
"lastName": {
"0": "The last name field is required."
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<ul ng-repeat="message in errormessage.error">
<li ng-repeat="(k,v) in message">
{{k}} - {{v}}
</li>
</ul>
</div>