【问题标题】:ng-repeat not working while traversing JavaScript array of objects遍历 JavaScript 对象数组时,ng-repeat 不起作用
【发布时间】:2016-05-24 10:52:13
【问题描述】:

这是我的控制器代码

var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController',['$scope','$http', function($scope, $http){
    $http.get($scope.something).success(function (data){
        $scope.items = data;
    });
    $scope.orders = [];
    $scope.process = function(item){
        var cart = '{"name":"'+item.name+'","price":"'+item.quantity*parseInt(item.price)+'","quantity":"'+item.quantity+'"}';
        $scope.orders.push(cart);
    }
}]);

基本上我有一个 PHP 页面,我在其中获取用户值并将元素动态添加到 $scope.orders 数组。

然后显示我正在使用此代码的数组元素

<div class="container" ng-repeat="order in orders">
    <h3>{{order.name}}</h3>
</div>

在我的 PHP 页面中。但没有显示任何内容。

【问题讨论】:

  • 因为cart 是一个字符串,而不是object
  • 问题不是因为字符串。你不是从 DOM 发送项目,或者如果你想从你已经在成功回调中调用的项目设置它,然后使用 forEach 循环单独的项目条目

标签: javascript php html arrays angularjs


【解决方案1】:

请注意,您不会在 $scope.orders 数组中推送对象,而是在推送对象的字符串化版本。

与 PHP 不同,JavaScript 解释并知道如何使用和浏览 JSON 对象。试试这个:

var myApp = angular.module('myApp',[]);

myApp.controller('restaurantController',['$scope','$http', function($scope, $http){
  $scope.orders = [];

  $http.get($scope.something)    // .success() is deprecated use .then() instead
    .then(function ( data ) {
      $scope.items = data;
    },
    function ( err ) {
      $scope.items = [];
    });

  $scope.process = function(item){
    var cart = { 
      name      : item.name,
      price     : item.quantity * parseFloat(item.price), 
      quantity  : item.quantity 
    };

    // Use .parseFLoat() because item price may not be an integer

    $scope.orders.push(cart);
  }
}]);

然后你就可以遍历$scope.orders Array。

【讨论】:

  • 谢谢它的工作。我没有注意到我正在传递一个字符串。
猜你喜欢
  • 2015-06-09
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多