0

Updating $scope values affects it's previous usage points.

After addPhrase call I use sayPhrase to update $scope

function PhrasesCtrl($scope) {
    $scope.trail = [0];

    $scope.addPhrase = function() {
        $scope.phrases.push({
            trail: $scope.trail
        });
    }

    $scope.sayPhrase = function(id) {
        // id = 1
        $scope.trail.push(id);
    }
}

Newly created Phrase have it's trail equal to [0], after sayPhrase call it becomes [0, 1]

After $scope.trail.push(id); my new element updates it's trail value.

How to keep used trail value away from changes?

4

1 回答 1

1

这是因为 JS 对象(和数组)仅通过引用传递。当您推入时,您将引用推trailphrases由 引用的同一数组$scope.trail

最简单的解决方案是通过创建一个新数组来打破对 的引用$scope.trail

    $scope.addPhrase = function() {
        $scope.phrases.push({
            trail: $scope.trail
        });
        $scope.trail = [0]; // I assume the `0` is on purpose
    }

现在$scope.trail每次addPhrase()调用都会重新开始。


或者,如果您需要保留 的当前内容trail,则应将该数组复制到一个新数组中。Angular 方便地为此提供了一种方法:

    $scope.addPhrase = function() {
        $scope.phrases.push({
            trail: angular.copy($scope.trail)
        });
    }
于 2013-09-07T16:18:58.817 回答