我想用$scope.push
但它仍有问题:
无法读取属性'推送'未定义的
我的JSON和JAVASCRIPT代码:
JSON
{"records":[{"total":"156000"}]}
JAVASCRIPT
$scope.plusCart = function() {
$http({
method : 'POST',
url : 'http://localhost/so-ku/www/server/menu/plus_cart',
headers : { 'Content-Type' : 'application/json' },
data : JSON.stringify({ rowid: $scope.currentItem.rowid, qty : $scope.currentItem.qty })
}).success(function(data) {
total_cart()
});
}
function total_cart() {
$http.get('http://localhost/so-ku/www/server/menu/total_cart').
then(function(response){
$scope.x = [];
$scope.x = response.data.records;
$scope.xtotal.push($scope.x.total);
});
}
HTML
<div ng-controller="CartCtrl">
<div ng-repeat="tot in xtotal" style="padding-top: 10px;">
Rp {{tot.total}}
</div>
</div>
注意:我想在提交plusCart之后,div会自动使用$scope.push
感谢。
答案 0 :(得分:1)
由于$ scope.xtotal未定义,数组推送显示错误
尝试以下
function total_cart() {
$http.get('http://localhost/so-ku/www/server/menu/total_cart').
then(function(response){
$scope.xtotal = []; ///define the veriable
$scope.x = [];
$scope.x = response.data.records;
$scope.xtotal.push($scope.x.total);
});
}
答案 1 :(得分:1)
根据 JSON:
{"records":[{"total":"156000"}]}
response.data.records
已经有一个数组[{"total":"156000"}]
。所以,没有必要再次在数组中分配它。
代码更正:
$scope.x = response.data.records
代替$scope.x = []
$scope.xtotal
的数组。工作演示:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
var jsonObj = {
"records":[{"total":"156000"}]
};
$scope.xtotal = [];
$scope.x = jsonObj.records;
$scope.xtotal.push($scope.x[0].total);
console.log($scope.xtotal);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="item in xtotal">
{{item}}
</div>
</div>
&#13;
答案 2 :(得分:0)
$ scope.x是一个数组。因为{&#34;记录&#34;:[{&#34;总&#34;:&#34; 156000&#34;}]}
如果要分配来自resonse.data.records的所有值,您只需执行以下操作:
$scope.xtotal = response.data.records;
如果你想手动做,是的,你需要将变量声明为数组:
$scope.xtotal = [];
for (var i = 0; i < $scope.x.length; i++) {
var obj = $scope.x[i];
// do your modification for an obj
// and push to your $scope.xtotal
$scope.xtotal.push(obj);
}
答案 3 :(得分:0)
因为$scope.x
(设置为response.data.records
)已经是您想要的数组
$scope.xtotal.push($scope.x.total);
应该只是
$scope.xtotal = $scope.x;
请参阅plunker:http://plnkr.co/edit/fo1kffVaIUKe3DrRDODN?p=preview