Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AngularJS "copy()" to avoid reference issues

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?

like image 731
peter Avatar asked Mar 24 '14 23:03

peter


People also ask

What is use of Angular copy?

copy when assigning value of object or array to another variable and that object value should not be changed. Without deep copy or using angular. copy, changing value of property or adding any new property update all object referencing that same object. var app = angular.

How can you copy the HTML element in AngularJS so that the original Oncopy element will not override?

AngularJS ng-copy Directive The ng-copy directive tells AngularJS what to do when an HTML element is being copied. The ng-copy directive from AngularJS will not override the element's original oncopy event, both the ng-copy expression and the original oncopy event will be executed.

Which method in angular creates a deep copy of variables?

The angular. copy function takes an object, array or a value and creates a deep copy of it.


1 Answers

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

like image 84
Christoph Avatar answered Oct 08 '22 21:10

Christoph