这是我的 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/