我正在尝试使用 json 对象动态生成复选框。
Controller
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 对象生成了复选框。我做错了什么?
最佳答案
您的代码存在问题,在以下行中,您使用新迭代的设施重新初始化数组 $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
});
});
});
});
});
关于javascript - 如何在angularjs中使用json对象生成复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509411/