2016-02-13 32 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

謝謝你的工作。我沒有注意到我正在傳遞一個字符串。 –