我正在尝试使用json对象动态生成复选框。
控制器
App.controller('amenitiesController',['$scope','$http', function($scope,$http){
var location_id = $('#location_id').val();
$http({method: 'GET', url: "/api/location/"+location_id+".json"}).
success(function(data, status) {
$.each(data.location.lodges, function(i,lodge) {
$.each(lodge, function(key,fac){
$.each(fac.facilities, function(index,f){
$scope.facilityNames = [ {name:f.facility.name,id:f.facility.id}];
console.log(f.facility.id,f.facility.name)
});
});
});
}).
error(function(data, status) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}]) ;
Html文件
<div class='col-md-2 searchdisplay-col1' ng-controller="amenitiesController" style="margin-top:50px">
<label ng-repeat="facilityName in facilityNames">
<input
type="checkbox"
name="{{facilityName.name}}"
value="{{facilityName.id}}"
ng-checked=""
ng-click=""
> {{facilityName.name}}
</label>
</div>
我从json成功获取了所有对象,但只为最后一个json对象生成了复选框。我做错了什么?
答案 0 :(得分:1)
您的代码问题在以下行中,您使用新迭代的facilty重新初始化数组$scope.facilityNames
。你应该在ajax请求之前声明一个空数组,然后在迭代时将facility
添加到先前创建的数组中。
$scope.facilityNames = [ {name:f.facility.name,id:f.facility.id}];
修改后的代码
$scope.facilityNames = []; //Initialize array
$http({
method: 'GET',
url: "/api/location/" + location_id + ".json"
}).
success(function (data, status) {
$.each(data.location.lodges, function (i, lodge) {
$.each(lodge, function (key, fac) {
$.each(fac.facilities, function (index, f) {
//add facility to array
$scope.facilityNames.push({
name: f.facility.name,
id: f.facility.id
});
});
});
});
});