javascript - 如何在angularjs中使用json对象生成复选框

标签 javascript jquery ajax json angularjs

我正在尝试使用 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/

相关文章:

javascript - 更改对象存储的主键值

javascript - 如何让工作网格显示来自 ajax 的数据源?

javascript - AJAX 发送表单中的所有字段

javascript - Firestore onSnapshot 通过 onEffect 中的状态附加到数组

javascript - 解析服务器注册无效 session token 错误

javascript - 禁用网页的浏览器缓存,不适用于 IE

javascript - 如何使用 jquery 检查 0 到 nth 索引复选框

javascript - 如果隐藏了 parent ,是否可以计算可见的 child ?

javascript - 如何在 jquery Font Awesome 图标之间切换

javascript - 如何传递 JSON 数据来更新 Highcharts 饼图