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

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

5 Comments

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...})
Sorry, I don't understand your question.
I mean Whether I can listen the page has already loaded event by angularjs and how to write the event ?
I find the answer here
thank you @p2004a , your suggestion help me solution a big problem,thanks a lot (-)

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.