【问题标题】:AngularJS and php array dataAngularJS 和 php 数组数据
【发布时间】:2013-07-17 12:42:22
【问题描述】:

我最近开始学习 AngularJS。当我从数据库中获取一个数组的数据时,我使用了foreach函数,所以我的代码是

<ul>
     <?php foreach($Items as $Item):?>
          <li><?php echo $Item['name'];?></li>
     <?php endforeach;?>
</ul>

我使用 AngularJS 是因为我需要可排序的列表元素。而我的AngularJS代码大致是

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

有可能吗?如果没有,如何获取从服务器接收到的数据,如果没有使用$http.post/get?

【问题讨论】:

  • 我最初的感觉是这样你将无法将ng-repeat和php forEach结合起来。
  • 您的代码不起作用吗?该代码对我来说看起来不错。你能显示 json_encode 的 JSON 输出吗?
  • 我认为最好不要在同一个文件中混合 PHP 和 JS 代码。为什么不使用 AJAX 来检索 Items 数组而不是使用 PHP 来回显它?
  • MaxPRafferty,此代码有效,但我不确定我在做什么正确,因为文档说模型应该在一个单独的文件中,那么也许我会发送数据通过 ajax

标签: php javascript angularjs angularjs-ng-repeat


【解决方案1】:

您可以使用ng-init 将模型保存在单独的文件中:

<ul ng-init="positions = <?php echo htmlspecialchars(json_encode($Items)); ?>">
    <li ng-repeat="position in positions | filter:query">
       <p>{{position.name}}</p>
    </li>
</ul>

【讨论】:

  • 重要的是要记住 ng-init 需要放在 ng-repeat 指令的父元素级别,就像这里一样.我试图把它放在同一个元素中,但没有成功
  • 另一点:javascript 中没有对象的排序。您需要使用数组在 javascript 中进行排序。因此,当使用 json_encode 时,数组顺序可能会受到影响。在您的ng-repeat 中,订单可能与原始数组中的不匹配。
猜你喜欢
  • 2016-02-21
  • 2014-10-31
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多