42

Here is a demo to my problem.

$scope.myNumbers = [10, 20, 30];

<div ng-repeat="num in myNumbers">
    <input type="text" ng-model="num">
    <div>current scope: {{num}}</div>
</div>

Can anyone explain to me why are the inputs uneditable/readonly? If it's by design, what's the rationale behind?

UPDATE 2/20/2014

It looks like this is no longer an issue for v1.2.0+ Demo. But do keep in mind that although the user controls are now editable with the newer angularJS versions, it is the num property in the child scopes, not the parent scope, that get modified. In another words, modifying the values in the user controls does not affect the myNumbers array.

4
  • Relevant AngularJS issue: github.com/angular/angular.js/issues/1267 Commented Sep 17, 2014 at 0:32
  • For anyone else looking for an answer, excepted one here is no longer valid. See one by sebnukem. Commented Oct 21, 2014 at 13:13
  • @FDIM - I am not sure if I understand what you are saying. The accepted answer (from Mark Rajcok) is still a valid solution, even for the newest Angular version (1.3). The approach of using $index is simply another working solution but it does not make the accepted answer invalid. Commented Oct 21, 2014 at 17:56
  • True, but its unnecessary complexity if version 1.3 used. I should have written that there is a better way, bad choice of words, sorry. Commented Oct 22, 2014 at 6:49

5 Answers 5

67

Can anyone explain to me why are the inputs uneditable/readonly? If it's by design, what's the rationale behind?

It is by design, as of Angular 1.0.3. Artem has a very good explanation of how 1.0.3+ works when you "bind to each ng-repeat item directly" – i.e.,

<div ng-repeat="num in myNumbers">
  <input type="text" ng-model="num">

When your page initially renders, here's a picture of your scopes (I removed one of the array elements, so the picture would have fewer boxes):

enter image description here (click to enlarge)

Dashed lines show prototypical scope inheritance.
Gray lines show child → parent relationships (i.e., what $parent references).
Brown lines show $$nextSibling.
Gray boxes are primitive values. Blue boxes are arrays. Purple are objects.

Note that the SO answer of mine that you referenced in a comment was written before 1.0.3 came out. Before 1.0.3, the num values in the ngRepeat child scopes would actually change when you typed into the text boxes. (These values would not be visible in the parent scope.) Since 1.0.3, ngRepeat now replaces the ngRepeat scope num values with the (unchanged) values from the parent/MainCtrl scope's myNumbers array during a digest cycle. This essentially makes the inputs uneditable.

The fix is to use an array of objects in your MainCtrl:

$scope.myNumbers = [ {value: 10}, {value: 20} ];

and then bind to the value property of the object in the ngRepeat:

<div ng-repeat="num in myNumbers">
  <input type="text" ng-model="num.value">
  <div>current scope: {{num.value}}</div>
Sign up to request clarification or add additional context in comments.

9 Comments

Mark, your answer has answered my desire to understand what's happening behind-the-scene. It's the type of answer I was looking for. Also, some of your other SO answers have helped me a lot. Thank you for sharing your knowledge and passion with the AngularJS community. Cheers.
So if you have an object with referencing ID's: myObj.myRef=[8,20], the only way is to convert this to [{value:1, value:2}] right? Would you then suggest to rather store references as strings myObj.myRef=["8","20"]?
@user785529, yes, you need an array of objects if you want to use ng-repeat and ng-model inside. Strings are primitives also, so they don't help solve the problem.
@Roylee, using "num.value" is the recommended practice: "always have a dot in your models" -- Miško video. In your controller, you would reference it as $scope.myNumbers[0].value.
@aidan - Mark has actually commented on the solution you mentioned in AngularJS's wiki. See it for yourself. Link
|
34

This problem is now addressed by more recent versions of AngularJS with the track by feature allowing repeaters over primitives:

<div ng-repeat="num in myNumbers track by $index">
  <input type="text" ng-model="myNumbers[$index]">
</div>

The page will not get repainted after each keystroke, which solves the problem of the lost focus. The official AngularJS doc is quite vague and confusing about this.

2 Comments

You are right that this is no longer an issue for v1.2.0+, but the use of track by isn't a factor here.
Thanks, actually using track by helped to not loose the focus on the input.
9

Seems that Angular is not able to write to model defined that way. Use reference to initial $scope attribute to let it bind value right way:

<div ng-repeat="num in myNumbers">
  <input type="text" ng-model="myNumbers[$index]">
</div>

8 Comments

Thanks Dmitry. Your solution works but not quite there. I can see the databinding is working but it's weird that the focus on the input is automatically gone after a keystroke. Take a look for yourself here.
Yep, it's caused by fact that angular updates view everytime you change model.
Avoid using $index for anything goes into controller. If you filter the data on the view via ngFilter. The index of the view would not refer to the index in the original array since the array in the view and model would be different.
Also, I am more interested to see why binding to the variable from the repeat expression (ie. num in this case) doesn't work, whether it's a bug or by design.
Actually, making editable collection with binded view is rather tricky task. If you are interested see please one of approaches to solve it: iweinfuld.posterous.com/…
|
9

ngRepeat uses a reference to the source array. Since integer (Number in js) is a value type, not a reference type, therefore cannot be passed by reference in javascript. The change will not be propagated.

Here is a demonstration:

   var x = 10;
   var ox = {value:10};

   var y = x;
   var oy = ox;

   y = 15
   oy.value = 15;

What would be the values of x and ox?

>> x = 10;
>> y = 15;
>> ox = {value:15};
>> oy = {value:15};

All javascript objects are passed by reference and all primitives are passed by value ["string", "number", etc].

Working plunker http://plnkr.co/edit/7uG2IvAdC2sAEHbdHG58

4 Comments

fastreload, your explanation makes sense but I am getting comflicting information. I read that ngRepeat creates a new copy of the value for each of its child scopes when the item is primitive. Please go to the section on ng-repeat of this SO answer
Mark's answer is more explanatory than mine on how do scopes work. But they are not conflicting answers. In my answer, I meant that y is copied by value whereas oy is copied by reference. And he also says "If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property."
That's good. I just want to make sure we are on the same page. With yours and Mark's explanation in mind, I was expecting that my inputs can be bind to the copy of the value and thus work with the copy. I guess AngularJS wants to make sure developers work with one single source of data so they made inputs binding to copy of the data uneditable in this case. Do you think that's the rationale behind?
It's not about angularjs, it is about how javascript works. Primitives are not mutable. Therefore has to be copied. In the example with x and y if you expect them to be equal. Then also it would be 15 = 10. If you want to read more, keywords are mutable, immutable, copy by value, copy by reference.
9

I had a similar issue (and also required 'add' and 'remove' functionality), and solved the problem like so:

$scope.topics = [''];
$scope.removeTopic = function(i) {
   $scope.topics.splice(i, 1); 
}

<div ng-repeat="s in topics track by $index">
    <input ng-model="$parent.topics[$index]" type="text">
    <a ng-click="removeTopic($index)">Remove</a>
</div>

<a ng-click="topics.push('new topic')">Add</a>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.