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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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?
That's the way JS works. If you put a variable into an array, you're storing its value, not the variable. See stackoverflow.com/questions/5865094/…
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. jsfiddle.net/h8xstepp
Thanks, and sorry about that. But hey, technically correct is always good! ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.