简体   繁体   中英

How do I format a PHP array for use with AngularJS' ng-repeat directive?

I have a table that I want to populate using ng-repeat . I'm having trouble figuring out how to format my array so that it works. Here is what I have so far:

PHP (customers.php):

$customer_array = array();

$customer1 = array(
  'customer_id' => '1',
  'name' => 'John Doe',
  'city' => 'New York'
);
$customer_array[] = $customer1;

$customer2 = array(
  'customer_id' => '2',
  'name' => 'Jane Doe',
  'city' => 'Boston'
);
$customer_array[] = $customer2;

echo($customer_array);

AngularJS Controller (CustomersCtrl.js):

$http({
    url: 'customers.php',
    method: "POST"
})
.success(function (data, status) {
    $scope.customers = data;
})
.error(function (data, status) {
    $scope.status = status;
});

HTML:

<table>
<tbody ng-controller="CustomersCtrl">
    <tr ng-repeat="customer in customers">
        <td>{{customer.customer_id}}</td>
        <td>{{customer.name}}</td>
        <td>{{customer.city}}</td>
    </tr>
</tbody>
</table>

This isn't working. What am I doing wrong?

UPDATE: I'm wondering if this is because I'm loading the HTML code from above using the code below:

$routeProvider.when('/customers.php', {
    templateUrl: 'partials/customers.html',
    controller: 'CustomersCtrl'
});

Is it because the newly loaded html template is not bound to the controller before it tries to do the ng-repeat loop?

You need to JSON encode the array before sending your response.

echo json_encode($customer_array);

That will give your javascript code something to work with. Right now the only thing getting passed back to your javascript is the word 'Array' which won't do anything.

If any body is having similar problems check if you have BOM marks in your JSON response.

What is BOM?

You can find that on wiki

How to check if you have BOM in your response?

  1. Open developer tools in chrome and go to network.
  2. Find your response file(something like file.php if you dont have htaccess rewrite) and click on it.
  3. There are 5 tabs one of them is response. There you will see a red dot if BOM marks are there.

What if you find red doot?

encode your files in utf-8 widouth BOM. In notepad++ you have an option in "encoding" tab.

PS: my english sucks and I know it :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM