Dowemo


Question:

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};


$this->load->view('home/index',$data);


now there is a view

//view


<div ng-controller="loadData">


     <ul>


        <!--one :when I init this page I need to show php data-->


        <?php foreach(users as user):?>


        <li><?=$user->name?>:<?=$user->email?><li>


        <?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">{{user.name}}:{{user.email}}</li>


    </ul>


</div>


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.

<script>


  var usersPrefetch = [


    <?php foreach(users as user):?>


    {"name": "<?=$user->name?>", "email": "<?=$user->email?>"},


    <?php endforeach?>


  ];


</script>


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.

EDIT:

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):?>


  <li><?=$user->name?>:<?=$user->email?><li>


  <?php endforeach?>


</ul>


<ul ng-if="users">


  <li ng-repeat="user in users">{{user.name}}:{{user.email}}</li>


</ul>


(Of course if you want to you can combine this two uls into one). Here is the suitable fiddle: https://jsfiddle.net/mser49aq/1/




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs