0 0 0 0


I'm new study angularjs , now there is a problem I hava no idea, please hlep me. thank you !

we use CodeIgniter NVC framework

//for example the controller is here
$data['users'] = {something from databases};

now there is a view

<div ng-controller="loadData">
        <!--one :when I init this page I need to show php data-->
        <?php foreach(users as user):?>
        <?php endforeach?>
        <!--two: but I must to update the users when others insert into users by ajax like
          the follow code -->
        <li ng-repeat="user in users">{{}}:{{}}</li>

how can I deal with the "one" and "two" show in above codes???

Best Answer:

What you are trying to do is to have a server and client side rendering simultaneously. Unfortunately, as far as I know AngularJS doesn't support this yet.

What you can do is to use only the AngularJS rendering and fetch users using Ajax just after the page load. I think it's the cleanest one.

Another solution is to render a JSON using PHP in a <script> and assign it to a global variable.

  var usersPrefetch = [
    <?php foreach(users as user):?>
    {"name": "<?=$user->name?>", "email": "<?=$user->email?>"},
    <?php endforeach?>

Then assign usersPrefetch to $scope.users in the controller and you are done. You will eliminate additional ajax request that way but in my opinion it's a quite dirty solution.


After a moment, I realized I have one more solution. You can prerender users list in one ul tag and use ngIf directive to switch to angular rendering after fetching new data from sewer using ajax.

<ul ng-if="!users">
  <?php foreach(users as user):?>
  <?php endforeach?>
<ul ng-if="users">
  <li ng-repeat="user in users">{{}}:{{}}</li>

(Of course if you want to you can combine this two uls into one). Here is the suitable fiddle:

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs