Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
My initial feeling is that you won't be able to combine ng-repeat and php forEach in this way. – itcouldevenbeaboat Jul 18 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? – MaxPRafferty Jul 18 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? – m4t1t0 Jul 18 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 – Yaroslav Osetrov Jul 18 at 14:25

1 Answer

up vote 1 down vote accepted

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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.