1

I am trying to organize my (elsewhere defined) variables in an array, but this breaks the two-way-binding. I don't understand why I can bind to a variable directly, but not indirectly. I guess this is some stupid mistake. Example here (jsfiddle) or below:

Html:

<div ng-controller="MyCtrl">
<input ng-model="test1"></input>
<input ng-model="test2[0]"></input>
<p>{{test1}}</p>
</div>

Javascript:

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.test1 = 'text goes here';
    $scope.test2 = [$scope.test1];
}

As you can see the first input is bound to the variable and updates it correctly, while the second one takes the initial value, but isn't bound.

F43nd1r
  • 7,690
  • 3
  • 24
  • 62

1 Answers1

1

It is working actually. See https://jsfiddle.net/ryekxkpL/2/

The $scope.test2[0] is a copy of $scope.test1, so it's the same as if you had $scope.test2 = ['text goes here']; Changing it won't effect $scope.test1.

kiswa
  • 14,737
  • 1
  • 21
  • 29
  • Thanks. Did I get you right: The binding works, but it binds to a copy? How do I prevent that it binds to a copy? – F43nd1r Jul 10 '15 at 11:54
  • 1
    That's the way JS works. If you put a variable into an array, you're storing its value, not the variable. See http://stackoverflow.com/questions/5865094/how-can-i-store-reference-to-a-variable-within-an-array#answer-5865121 – kiswa Jul 10 '15 at 11:55
  • I accepted the answer, because it is technically correct, altough it does not solve the problem itself. I'm going to try to wrap these primitive variables in an object, so I can copy the reference to the object to the array. Edit - That works. It requires a bit more code though. https://jsfiddle.net/h8xstepp/ – F43nd1r Jul 10 '15 at 12:05
  • Thanks, and sorry about that. But hey, technically correct is always good! ;) – kiswa Jul 10 '15 at 12:07
  • @F43nd1r Try http://stackoverflow.com/questions/1686990/javascript-variable-reference-alias – Moby Disk Jul 10 '15 at 12:12
  • @Moby Disk thats what I did. – F43nd1r Jul 10 '15 at 12:53