Rajib
Rajib

Reputation: 592

angular one way binding

I am using angular 1.3.15. I want to bind data, such a way that, first time variable($scope.twotap_builtin_cart.sites[sikey].shipping ) assigned data from $scope.shipping_address. Later on even if , variable named $scope.twotap_builtin_cart.sites[sikey].shipping data modified, it should not haveve any impact on other $scope.shipping_address. I am talking about one time binding or one way binding

Upvotes: 0

Views: 175

Answers (3)

ryder
ryder

Reputation: 897

A similar requirement was asked in this question: Edit with bootstrap modal and angulajs

Similarly, you can use the AngularJS copy function to replicate your data without any lingering bindings.

$scope.twotap_builtin_cart.sites[sikey].shipping = angular.copy($scope.shipping_address);

Here we are copying the value from $scope.shipping_address into the other variable. Now even if you make a change to $scope.twotap_builtin_cart.sites[sikey].shipping, this will not be reflected in $scope.shipping_address - which is what you want.

Upvotes: 2

FDavidov
FDavidov

Reputation: 3675

I think that you are not looking for binding but simply assigning a value of a variable to another. When working with JSON objects (and $scope is one such object), making a = b is NOT copying the contents of b to a, but making both a and b reference the same object. The best way is to perform the assignment as:

b = JSON.parse(JSON.stringify(a)) ;

In your case:

$scope.twotap_builtin_cart.sites[sikey].shipping = JSON.parse(JSON.stringify($scope.shipping_address)) ;

One you do this, both variables hold the same information but they can be changed without affecting the other.

Upvotes: 2

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

you should use angular.copy() for deep coping

$scope.shipping_address = angular.copy($scope.twotap_builtin_cart.sites[sikey].shipping)

this way even if $scope.twotap_builtin_cart.sites[sikey].shipping modify its not gonna bind to the $scope.shipping_address

Upvotes: 2

Related Questions