在AngularJS中向现有数组推送JSON数据

3

我在向一个已有的数组中推送数据时遇到了问题。你可以看到我正在将数据发布到表格中,但是当用户输入8位条形码时,我希望将数据推送到表格中。

在此输入图片描述

工厂

    angular.module('app.pickUpServ', []).factory('pickUpServ', ['$rootScope', '$http',
    function($rootScope, $http) {
        return {
            getPickUpList: function(data) {
                $http({
                    method: 'POST',
                    url: 'app/Service/CourierService.asmx/BarcodeList',
                    data: {
                        "bardcodeVal": "",
                        "courierType": "PICKUP",
                        "userName": "aspuser"
                    },
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                }).success(data).error(function(error) {
                    console.log('Error - getPickUpList');
                });
            },
            items: [{
                        "bardcodeVal": "",
                        "courierType": "PICKUP",
                        "userName": "aspuser"
                    }],
            add: function(item) {
                this.items.push(item);
                console.log(item);
            }
        };
    }
]);

控制器

angular.module('app.scanListCtrl', []).controller('ScanListCtrl', ['$scope', 'pickUpServ',
    function ($scope, pickUpServ) {
        //Get Pick Up Data
        if ($scope.title == 'Pick Up') {

            pickUpServ.getPickUpList(function (data) {
                $scope.items = data.d
            });

            $scope.autoAddItem = function () {
                if (($scope.BarcodeValue + '').length == 8) {
                    pickUpServ.add({
                        "barcodeVal": $scope.BarcodeValue,
                        "courierType": "PICKUP",
                        "userName": "aspuser"
                    });
                    $scope.BarcodeValue = "";
                }
            };
        }
    }
]);

HTML

<div ng-controller="ScanListCtrl">
<div class="row prepend-top-md">
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">
                    <i class="fa fa-barcode"></i>&nbspScan Item</h3>
            </div>
            <div class="panel-body">
                <div class="input-group input-group-lg">
                    <input type="number" class="form-control" placeholder="Scan Item" ng-model="BarcodeValue"
                        ng-change="autoAddItem()" is-focus>
                    <span class="input-group-btn">
                        <button class="btn btn-info" type="button" ng-click="addRow()">
                            Add Barcode</button>
                    </span></div>
            </div>
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th class="text-center" style="width: 3%">
                            #
                        </th>
                        <th>
                            <i class="fa fa-barcode"></i>&nbspBarcode
                        </th>
                        <th>
                            <i class="fa fa-medkit"></i>&nbspCSN
                        </th>
                        <th>
                            <i class="fa fa-user"></i>&nbspUser
                        </th>
                        <th>
                            <i class="fa fa-clock-o"></i>&nbspDate
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in items | orderBy:'Id':true:reverse">
                        <td class="text-center">
                            [{{item.Id}}]
                        </td>
                        <td>
                            {{item.BarcodeValue}}
                        </td>
                        <td>
                            {{item.CSN}}
                        </td>
                        <td>
                            {{item.LastName + ', ' + item.FirstName}}
                        </td>
                        <td>
                            {{item.Created}}
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>


1
在你的控制器中,你将 $scope.items 赋值了两次。你对 pickUpServ.items 的原始引用被一个从 POST 请求返回的新项目数组所替换。这是有意为之吗? - Decade Moon
谢谢。我能看到那个小错误。但是我仍然在尝试将数据推送到表中遇到问题。 - Davis
1
我建议你在服务/工厂中完成所有的数组操作。这样,你只需要调用 pickUpServ.add(),然后在路由的 resolve 方法中使用 pickUpServ.get()。 - Cory Silva
@CorySilva - 感谢您的建议。我喜欢尝试在控制器中使用add()。 - Davis
2个回答

4

您正在向范围之外的其他元素(在工厂内部)添加新项目,必须执行以下操作:

        $scope.autoAddItem = function () {
            if (($scope.BarcodeValue + '').length == 8) {
                $scope.items.push({
                    "barcodeVal": $scope.BarcodeValue,
                    "courierType": "PICKUP",
                    "userName": "aspuser"
                });

                $scope.BarcodeValue = "";
            }
        };

如果您想让工厂内的所有内容都像这样(忽略上面的更改):
angular.module('app.pickUpServ', []).factory('pickUpServ', ['$rootScope', '$http',
function($rootScope, $http) {
    return {
        getPickUpList: function(callback) {
            var _this = this; 
            $http({
                method: 'POST',
                url: 'app/Service/CourierService.asmx/BarcodeList',
                data: {
                    "bardcodeVal": "",
                    "courierType": "PICKUP",
                    "userName": "aspuser"
                },
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
            })
            .success(function(data) {
            _this.items = data.d;
            callback(_this.items) //This gonna set to $scope the items in factory and angular  
                              //link the object items to $scope.items (Code not tested but must work)
            })
            .error(function(error) {
                console.log('Error - getPickUpList');
            });
        },
        items: [{
                    "bardcodeVal": "",
                    "courierType": "PICKUP",
                    "userName": "aspuser"
                }],
        add: function(item) {
            this.items.push(item);
            console.log(item);
        }
    };
}
]);

我在使用 data(_this.items) 时遇到了“TypeError: object is not a function”错误。 - Davis
你能提供另一种解决方案吗? - Davis
1
修复了一个错误,传递回调方法时被覆盖的问题。(已被函数重写) - Jesús Quintana
还是不行吗?无论如何,我找到解决方法了...我使用了$rootScope全局变量。 - Davis
另一种解决方案是将$scope作为工厂的参数传递,类似于这样: function($scope ,item) { $scope.items.push(item); console.log(item); }我真的不建议将垃圾设置到rootScope中,最好传递$scope。 ($rootScope存在于整个应用程序中,而$scope仅存在于当前控制器中) - Jesús Quintana
1
很奇怪,我有一个完全相同的代码,用于Angular服务聊天应用程序,并将消息保存在服务对象中,作用域正常。唯一不同的是我的服务有一个getter来获取对象,类似于这样getItems:function(){return this.items};祝你的项目好运。 - Jesús Quintana

1

问题解决了...我使用了$rootScope.items = data.d;来解决我的问题。谢谢大家的帮助!

工厂

angular.module('app.pickUpServ', []).factory('pickUpServ', ['$rootScope', '$http',
    function($rootScope, $http) {

        return {
            getPickUpList: function(data) {
                $http({
                    method: 'POST',
                    url: 'app/Service/CourierService.asmx/BarcodeList',
                    data: {
                        "bardcodeVal": "",
                        "courierType": "PICKUP",
                        "userName": "aspuser"
                    },
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                }).success(function(data){
                    $rootScope.items = data.d;
                    console.log(data.d);
                }).error(function(error) {
                    console.log('Error - getPickUpList');
                });
            },
            items: [],
            add: function(item) {
                $rootScope.items.push(item);
                console.log(item);
            }
        };
    }
]);

控制器

angular.module('app.scanListCtrl', []).controller('ScanListCtrl', ['$scope', 'pickUpServ',
    function ($scope, pickUpServ) {
        //Get Pick Up Data
        if ($scope.title == 'Pick Up') {
            //$scope.items = pickUpServ.items;

            pickUpServ.getPickUpList(function (data) {
                $scope.items = data.d
            });

            $scope.autoAddItem = function () {
                if (($scope.BarcodeValue + '').length == 8) {
                    pickUpServ.add({
                        "barcodeVal": $scope.BarcodeValue,
                        "courierType": "PICKUP",
                        "userName": "aspuser"
                    });
                    $scope.BarcodeValue = "";
                }
            };
        }
    }
]);

你是否使用任何数据库系统来进行存储? - Kushal Jayswal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接