0

Once I realized how ng-model directive works and was absolutely confident about it's behaviour this example just blowed my mind

<html ng-app>
<head>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body ng-init="names = ['Sam', 'Harry', 'Sally']">
    <h1>Fun with Fields and ngModel</h1>
    <p>names: {{names}}</p>
    <h3>Binding to each element directly:</h3>
    <div ng-repeat="name in names">
        Value: {{name}}
        <input ng-model="name">                         
    </div>
    <p class="muted">The binding does not appear to be working: the value in the model is not changed.</p>
    <h3>Indexing into the array:</h3>
    <div ng-repeat="name in names">
        Value: {{names[$index]}}
        <input ng-model="names[$index]">                         
    </div>
    <p class="muted">Type one character, and the input field loses focus. However, the binding appears to be working correctly.</p>
</body>

ng-repeat fiddle. Main problem is angular's behaviour for three different versions. I understand that ng-repeat creates a new scope for each array item, I suppose (not sure) it tracks only array reference and it's size (so, array items shouldn't cause $digest loop on change), but, what we've got here (watch just first example without $index using): for version 1.0.3 < we have expected behaviour: changing 'name' property with input will only change ngModelController's value (scope inheritance) and this is fair, 1.1.1 - well, what's going on there: we don't even get new values inside of input and! we don't rerender our items cause we don't lose the focus (and i really don't understand why $digest loop fires value replacement for this input as Artem has said), third version - 1.2.1: changing input values also changes 'name' value in the outer scope (as I understand ngModelController should inherit a scope created by ng-repeat directive). So, what really happens (and why) in all three examples?

Community
  • 1
  • 1
starbeast
  • 103
  • 3
  • 8

1 Answers1

0

Using Angular latest version (1.2.1) and track by $index. This issue is fixed

http://jsfiddle.net/rnw3u/55/

    <div ng-repeat="name in names track by $index">
        Value: {{names[$index]}}
        <input ng-model="names[$index]">                         
    </div>
Thilaga
  • 1,591
  • 1
  • 13
  • 13