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

friker
  • 3
  • 2

1 Answers1

1

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/

p2004a
  • 133
  • 2
  • 7
  • the variables of usersPrefetch we can destory of it, when after loaded the page , would you konw how to listen to the loded page like jquery $(function(){ //your code here...}) – friker Mar 30 '15 at 08:51
  • Sorry, I don't understand your question. – p2004a Mar 30 '15 at 08:58
  • I mean Whether I can listen the page has already loaded event by angularjs and how to write the event ? – friker Mar 30 '15 at 09:03
  • I find the answer [here](http://stackoverflow.com/questions/21715256/angularjs-event-to-call-after-content-is-loaded) – friker Mar 30 '15 at 09:20
  • thank you @p2004a , your suggestion help me solution a big problem,thanks a lot (*-*) – friker Mar 30 '15 at 09:23