最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using AngularJS "copy()" to avoid reference issues - Stack Overflow

programmeradmin5浏览0评论

I'm displaying a list of items, each of which has an "edit"-button next to it. A click on that opens an angular ui modal window and the user can change some properties of the specific item.

Now, what bugged me was that when typing in this edit-window, the specific item in the list of items reflected the changes immediatly. I only wanted it to update when the user clicked 'ok' in the modal, and to not change at all if the user chose 'cancel'.

My workaround uses copy to make a, well, copy of the chosen item that then serves as model for the view:

var modalInstance = $modal.open({
    templateUrl: 'scripts/app/views/editBond.html',
    controller: function ($scope, $modalInstance, bond) {
        $scope.bond = angular.copy(bond);
        $scope.ok = function () {
            $modalInstance.close($scope.bond);
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    },
    resolve: {
        bond: function () {
            return bond;
        }
    }
});

Is using angular.copy() appropriate to avoid such issues? Is this a scope issue at all?

I'm displaying a list of items, each of which has an "edit"-button next to it. A click on that opens an angular ui modal window and the user can change some properties of the specific item.

Now, what bugged me was that when typing in this edit-window, the specific item in the list of items reflected the changes immediatly. I only wanted it to update when the user clicked 'ok' in the modal, and to not change at all if the user chose 'cancel'.

My workaround uses copy to make a, well, copy of the chosen item that then serves as model for the view:

var modalInstance = $modal.open({
    templateUrl: 'scripts/app/views/editBond.html',
    controller: function ($scope, $modalInstance, bond) {
        $scope.bond = angular.copy(bond);
        $scope.ok = function () {
            $modalInstance.close($scope.bond);
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    },
    resolve: {
        bond: function () {
            return bond;
        }
    }
});

Is using angular.copy() appropriate to avoid such issues? Is this a scope issue at all?

Share Improve this question asked Mar 24, 2014 at 23:08 peterpeter 2,1037 gold badges25 silver badges51 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

Yep, using angular.copy() is absolutely appropriate here. If you want something more advanced you might want to checkout angular-history

发布评论

评论列表(0)

  1. 暂无评论