Using AngularJS "copy()" to avoid reference issues

All we need is an easy explanation of the problem, so here it is.

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?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply