2016-02-13 65 views
1

的JavaScript数组这是我的控制器代码NG重复不工作时,穿越的对象

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); 
    } 
}]); 

基本上我有在那里我得到了用户价值和动态将元素添加到$ scope.orders阵列一个PHP页面。

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

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

在我的PHP page.But没有显示。

+3

因为'cart'是一个**字符串**,而不是_object_ – Tushar

+0

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

回答

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数组。

+0

谢谢你的工作。我没有注意到我正在传递一个字符串。 –