Angularjs data binding when passing a reference? -


sometimes, when 2 variables refer same variable, not binding this:

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

when change $scope.a, $scope.b not change. see plunker

however, binding together, example happens me in modal 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 $modalinstance represents modal window (instance) dependency. // not same $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 plunker. here "modaldata1" , "modaldata2" both referring "data". in modal of plunker, change modaldata1, modaldata2 changes it.

why this??

thank you!

update:
should copy element, because since javascript pass-by-reference both of variables (references) in fact pointing same object. if want remove side effect have copy object before assigning:

$scope.modaldata1 = angular.copy(data); $scope.modaldata2 = angular.copy(data); 

plunker

original answer:

in example you've provided modaldata2 input changing modaldata1, because have same model assigned in ng-model attribute:

<div class="modal-body">     modaldata1:     <input ng-model="modaldata1" />     <br>     modaldata2:     <input ng-model="modaldata1" /> </div>    

when fix it, independent (plunker):

<div class="modal-body">     modaldata1:     <input ng-model="modaldata1" />     <br>     modaldata2:     <input ng-model="modaldata2" /> </div>    

then when update modaldata1 input, other not change.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -