Tong Tong - 16 days ago 5
AngularJS Question

Angularjs data binding when passing a reference?

Sometimes, when two variables refer to the same variable, they are not binding together like this:

var option = 1;
$scope.a = option;
$scope.b = option;


When you change $scope.a, $scope.b does not change. See this Plunker

However, sometimes they are binding together, for example it happens to me in a modal like this:

angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function($scope, $modal, $log) {

$scope.testDataArray = [{
"name": "Doe"
}, {
"name": "Deer"
}, {
"name": "Female"
}];


$scope.open = function(testData) {

var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
data: function() {
return testData;
}
}
});

modalInstance.result.then(function(selectedItem) {
$scope.scopeData = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
};

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

var ModalInstanceCtrl = function($scope, $modalInstance, data) {
$scope.modalData1 = data;
$scope.modalData2 = data;

$scope.ok = function() {
$modalInstance.close($scope.modalData);
};

$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};


See the Plunker.
Here "modalData1" and "modalData2" are both referring to "data".
In any modal of this Plunker, you change modalData1, then modalData2 changes with it.

Why it is like this??

Thank you!

Answer

UPDATE:
You should copy the element, because since javascript is pass-by-reference both of this variables (references) are in fact pointing to the same object. If you want to remove that side effect you have to copy object before assigning:

$scope.modalData1 = angular.copy(data);
$scope.modalData2 = angular.copy(data);

plunker

ORIGINAL ANSWER:

In example you've provided modalData2 input is changing with modalData1, because they have the same model assigned in ng-model attribute:

<div class="modal-body">
    modalData1:
    <input ng-model="modalData1" />
    <br>
    modalData2:
    <input ng-model="modalData1" />
</div>   

When I fix it, then they are independent (plunker):

<div class="modal-body">
    modalData1:
    <input ng-model="modalData1" />
    <br>
    modalData2:
    <input ng-model="modalData2" />
</div>   

Then when you update modalData1 input, then the other does not change.

Comments