2

I recently started learning AngularJS. When I getting data from the database an array, I using function foreach, so my code is

<ul>
     <?php foreach($Items as $Item):?>
          <li><?php echo $Item['name'];?></li>
     <?php endforeach;?>
</ul>

I use AngularJS because I need sortable list elements. And my code with AngularJS roughly the

<script>
     function PositionsList($scope){
         $scope.positions=<?php echo json_encode($Items);?>
     }
</script>
<ul>
    <li ng-repeat="position in positions | filter:query">
       <p>{{position.name}}</p>
    </li>
</ul>

Is it possible to do so? If not, how to get the data received from server, If not use $http.post/get?

4
  • My initial feeling is that you won't be able to combine ng-repeat and php forEach in this way. Commented Jul 18, 2013 at 14:03
  • 1
    Does your code not work? That code looks good to me. Could you show the JSON output of the json_encode? Commented Jul 18, 2013 at 14:13
  • 1
    I think is better not to mix PHP an JS code in the same file. Why do not use AJAX to retrieve the Items array instead of echoing it with PHP? Commented Jul 18, 2013 at 14:18
  • MaxPRafferty, This code works, but I'm not sure what I'm doing this right, because the documentation says that the model should be in a separate file, then maybe I'll be send data via ajax Commented Jul 18, 2013 at 14:25

1 Answer 1

8

You can use ng-init to keep your model in a separate file:

<ul ng-init="positions = <?php echo htmlspecialchars(json_encode($Items)); ?>">
    <li ng-repeat="position in positions | filter:query">
       <p>{{position.name}}</p>
    </li>
</ul>
2
  • It's important to remember that ng-init needs to be placed in a parent element level of the ng-repeat directive, exactly like is here. i was trying to put it in the same element and getting no success Commented Aug 13, 2015 at 15:26
  • Another point: there's no sorting of objects in javascript. You need to use an array for sorting in javascript. So when using json_encode the array order may be affected. And inside your ng-repeat the order may not match the one in original array. Commented Nov 8, 2016 at 16:09

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.