为什么 push 函数会影响数组中的其他对象



我的应用程序中存在一个问题:我正在尝试将音符数组推送到音符数组中,但是当第二个数组被推入音符时,音符中的所有对象都变得相同。

这是我的 angularJS 控制器:

var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
    $scope.note = {};
    $scope.notes = [];
    $scope.submit = function() {
        $scope.notes.push($scope.note);
    };    
});

网页代码:

    <div data-ng-controller="noteCtrl">
        <form name="noteForm" data-ng-submit="submit()">
            <div class="col-md-9 col-sm-12 col-xs-12">
                <div class="row">
                    <div class="col-xs-12 bdr">
                        <input class="full" type="text" name="title" data-ng-model="note.title" placeholder="Note title is required" required />
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12 bdr">
                        <textarea class="full" name="content" data-ng-model="note.content" placeholder="Input the note content here"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 col-sm-4 col-xs-12 bdr">
                        <button class="full" type="reset" data-ng-click="">Cancel</button>
                    </div>
                    <div class="col-md-4 col-sm-4 col-xs-12 bdr">
                        <button class="full" type="button" data-ng-disabled="noteForm.$invalid" data-ng-click="">Save</button>
                    </div>
                    <div class="col-md-4 col-sm-4 col-xs-12 bdr">
                        <button class="full" type="submit" data-ng-disabled="noteForm.$invalid">Publish</button>
                    </div>
                </div>
            </div>
        </form>
        {{note}}
        {{notes}}
    </div>

例如,我将两个不同的对象(当然具有不同的值)推入笔记中。将第二个推入其中后,注释将如下所示:

[{"title":"aaaa","content":"bbbb"},{"title":"aaaa","content":"bbbb"}]

提前谢谢。

我认为注释最初应该具有属性,推送后应该重置它。

app.controller("noteCtrl", function ($scope) {
    $scope.note = { title: "", content: "" };
    $scope.notes = [];
    $scope.submit = function() {
        $scope.notes.push($scope.note);
        $scope.note = { title: "", content: "" };
    };    
});

这是针对对象范围。 您应该在函数体中定义对象。

$scope.submit = function() {
    var note = {"title":"","content":""};
    $scope.notes.push(note);
};  

最新更新