如何迭代内部对象';AngularJS模板中的属性?
我正在学习AngularJS。我想打印出一个对象列表,并迭代对象的一个内部对象属性。这看起来像是一个使用嵌套循环的标准过程,然而,它看起来并不是那么简单 我的控制器设置如下。本质上,它是一个随机车辆列表如何迭代内部对象';AngularJS模板中的属性?,angularjs,angularjs-ng-repeat,Angularjs,Angularjs Ng Repeat,我正在学习AngularJS。我想打印出一个对象列表,并迭代对象的一个内部对象属性。这看起来像是一个使用嵌套循环的标准过程,然而,它看起来并不是那么简单 我的控制器设置如下。本质上,它是一个随机车辆列表 var vehicleApp = angular.module("vehicleApp", []); vehicleApp.controller('VehicleController', function ($scope) { $scope.vehicles = [{
var vehicleApp = angular.module("vehicleApp", []);
vehicleApp.controller('VehicleController', function ($scope) {
$scope.vehicles = [{
id: 0,
name: "car",
parts: {
wheels: 4,
doors: 4
}
}, {
id: 1,
name: "plane",
parts: {
wings: 2,
doors: 2
}
}, {
id: 2,
name: "boat",
parts: {
doors: 1
}
}];
});
我想将车辆输出为:
car
- wheels (4)
- doors (2)
plane
- wings (2)
- doors (2)
boat
- doors (1)
我使用的模板设置如下:
<div ng-app="vehicleApp" ng-controller="VehicleController">
<p ng-repeat="vehicle in vehicles">
{{ vehicle.name }}
</p>
<ul>
<li ng-repeat="(attribute, value) in vehicle.parts">
{{attribute}} ({{value}})
</li>
</ul>
</div>
{{vehicle.name}
-
{{attribute}}({{value}})
这将生成车辆列表,但不会生成零件内部对象的子列表
有趣的是,当我使用
{{vehicle.parts}}
时,它返回parts内部对象的JSON字符串。AngularJS是否将其视为字符串,因此无法打印零件对象的属性?您没有将第二个ngRepeat
括在第一个中:
<div ng-app="vehicleApp" ng-controller="VehicleController">
<p ng-repeat="vehicle in vehicles">
{{ vehicle.name }}
<ul>
<li ng-repeat="(attribute, value) in vehicle.parts">
{{attribute}} ({{value}})
</li>
</ul>
</p>
</div>
{{vehicle.name}
-
{{attribute}}({{value}})
更改此选项不会更改输出。然而,当我将更改为a时,它确实起了作用。我想它要求HTML格式正确?@user2708395是的,HTML格式必须正确。你能做一把小提琴来说明问题吗这是把当作包装的小提琴。将其更改为div可以使其正常工作。谢谢你的快速回答@user2708395好吧,这真的很奇怪……对不起,我说不出问题出在哪里。问题是否与HTML验证有关,块元素只能包含内联元素?如果我将列表改为使用的,它会再次工作。