javascript - 无法读取未定义的 Angular JS 的属性 'push'

标签 javascript angularjs json

我想用$scope.push自动更改div

但仍然有问题:

无法读取未定义的属性“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 更改值

谢谢。

最佳答案

根据您的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);
});
<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>

关于javascript - 无法读取未定义的 Angular JS 的属性 'push',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40986054/

相关文章:

JavaScript 对象到 JSON Node-RED

javascript - Videojs Player HD 切换更改

javascript - 找不到网页 JavaScript 错误

c# - 如何防止网页刷新

javascript - 是否可以在 AngularJS 中的资源上设置默认查询参数?

json - 如何将 PIL 图像转换为 JSON 可序列化字符串,反之亦然?

javascript - 如何使用 jquery 创建测验结果

javascript - 如何避免 JavaScript/AngularJS 中的 HTTP 请求竞争条件?

javascript - Electron + angularjs IPC机制

java - 创建动态类型列表