Angularjs 推送到服务中的阵列替换了以前的项目

Angularjs push to array in service replaces previous items

我正在尝试使用 ionic 和 angularjs.

添加到 home.html 中的列表并在 myOrders.html 中显示列表

问题是,当我将新项目推送到数组时,以前的项目会被新项目替换。

示例:

push 'one' -> array is [{'name':one'}]

push 'two' -> array is [{'name':'two'},{'name':'two'}] // should be [{'name':'one'},{'name':'two'}]

push 'three' -> array is [{'name':'three'}, {'name':'three'}, {'name':'three'}] // should be [{'name':'one'},{'name':'two'},{'name':'three'}]

我在下面添加了我的代码的相关部分。

home.html(添加到列表)

<ion-view title="Home">
    <ion-content ng-controller="homeCtrl">
        <form ng-submit="submitForm(product)" class="list">
            <input ng-model="product.name" type="text">
            <input type="submit" value="Search" class="button">
        </form>          
    </ion-content>
</ion-view>

myOrders.html(显示列表)

<ion-view title="My Orders">
    <ion-content ng-controller="myOrdersCtrl">
        {{ product }}
    </ion-content>
</ion-view>

controllers.js

angular.module('app.controllers', [])
...
.controller('homeCtrl', function($scope, $state, formData) {
        $scope.product = {};

        $scope.submitForm = function(product) {
            if (product.name) {
                formData.updateForm(product);
                $state.go('menu.myOrders');
            } else {
                alert("Please fill out some information for the user");
            }
        };
    })

.controller('myOrdersCtrl', function($scope, formData) {
    $scope.product = formData.getForm();
})

services.js

angular.module('app.services', [])

.service('formData', [function(){
    return {
        form: [],
        getForm: function() {
            return this.form;
        },
        updateForm: function(item) {
            this.form.push(item);
        }
    }
}]);

您一次又一次地向数组中插入相同的对象。由于对象总是按引用传递,因此同一对象的引用被推入数组。当您更新对象时,存储在数组中的所有引用都会更改。

尝试创建对象的副本,同时传递给 updateForm()

.controller('homeCtrl', function($scope, $state, formData) {
        $scope.product = {};

        $scope.submitForm = function(product) {
            if (product.name) {
                formData.updateForm(angular.copy(product));
                $state.go('menu.myOrders');
            } else {
                alert("Please fill out some information for the user");
            }
        };
    })