javascript - ng-repeat 在遍历 JavaScript 对象数组时不起作用

标签 javascript php html arrays angularjs

这是我的 Controller 代码

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 页面中。但没有显示任何内容。

最佳答案

请注意,您没有将对象推送到 $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 数组。

关于javascript - ng-repeat 在遍历 JavaScript 对象数组时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35377005/

相关文章:

php - 如何在表单提交事件中从 PHP 调用 javascript 函数

php - 如何通过 PHP 访问 AWS S3?

php - 如何在 Laravel 4 中更新字段的列?

php - CodeIgniter 中的图像处理

javascript - 我可以将变化的变量保存到sql中吗?

javascript - 不同标记的重复点击事件监听器: google maps

Javascript onkeyup 也是 "slow"吗? .hide() 仅适用于 onkeydown

javascript - react Hook : get state of useState inside a listener

html - 元素未居中。我用的是绝对?

javascript - 悬停弹出菜单不适用于导航子链接