0

I am trying to generate checkboxes dynamically using json objects.

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 file

<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>

I get all the objects from json successfuly, but the checkbox is generated only for the last json object. What am i doing wrong?

0

1 Answer 1

1

Problem with your code is in following line, Where you are re-initialize your array $scope.facilityNames with newly iterated facilty. You should declare an empty array before ajax request, then on iteration add facility to previously created array.

 $scope.facilityNames =  [ {name:f.facility.name,id:f.facility.id}];

Modified Code

$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
                });
            });
        });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.