0

Having problem printing the angular http response array?

I'm having a problem printing the array response in my site in codeigniter. I'm trying to loop an angular response array in the select option. While I printed the response array the array seems to be in proper format but the looping is not happening.

<body>
  <div ng-app="app" ng-controller="ctrl">
    <select ng-model="selectedname" ng-options="x.id for x in names"></select>
    <table>
      <tr ng-repeat="x in names">
        <td>{{ x.id }}</td>
      </tr>
    </table>
    <!--<p>You selected : {{ selectedname.id }}</p><p>with color {{selectedname.id }}</p>-->
    <p>{{ names }}</p>
  </div>

</body>

<script>
  var app = angular.module('app', []);

  app.controller('ctrl', function($scope, $http) {
    $http.get("<?php echo base_url().'ap/load_data' ?>").then(function(response) {
      $scope.names = response.data.rec;
    });
  });
</script>

public function load_data(){
    
    $this->load->model('record');
    $data = $this->record->load_all();
    $out = '';
    
    foreach($data as $d){
        if($out){ $out .= ","; }
        $out .= "{'id': '".$d['id']."',";
        $out .= "'subname': '".$d['subname']."'}";
    }
    //$test = "{'rec' : [$out]}";
    $test = "[$out]";
    echo json_encode(array('rec' => $test));            
}

As you can see the below {{ names }} prints the following array

[
    {'id': '1','subname': 'melbourne'},
    {'id': '2','subname': 'sydney'},
    {'id': '3','subname': 'mumbai'},
    {'id': '4','subname': 'pune'},
    {'id': '5','subname': 'tokyo'},
    {'id': '6','subname': 'osaka'}
]

But the array is not getting used to create the select picker with the values. I'm new to angularjs so the solution might be simple but I'm not getting it. Any help is appreciated. Thanks.

2
  • 1
    Shouldn't it be ng-options="x as x.subname for x in names" Commented Mar 30, 2019 at 19:17
  • Tried that prints empty select picker. Commented Mar 30, 2019 at 19:24

1 Answer 1

2

Just Try

$out =array();
foreach($data as $d){
    array_push($out, $d);        
}
echo json_encode(array('rec' => $out));
Sign up to request clarification or add additional context in comments.

3 Comments

It worked man thanks. Can you tell me what the problem was. I think my response array was not well structured was that it.
Thank you.This line is value stored in string formate $out .= "{'id': '".$d['id']."',"; $out .= "'subname': '".$d['subname']."'}"; and your are stored one array and again you are tried to convert json value that is problem. so you are got it not well structured data
okay, actually I was following a tutorial from a website. Thanks again.

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.