2

I'd like to know why I can't input more than one character per input in this example:

http://jsfiddle.net/R3uY4/2/

<div ng-app>
  <div ng-controller="ctrl">
     <table>
            <tr>
                <td ng-repeat="f in foo">
                    <input ng-model="foo[$index]" style="width:60px" ></input>
                </td>
            </tr>
        </table>
  </div>
</div>

js:

function ctrl($scope) {
  $scope.foo = [];
    for (var i=0; i<5; i++) {
        $scope.foo.push('');
    }  
}
plus-
  • 45,453
  • 15
  • 60
  • 73

2 Answers2

5

You are binding your model to a primitive. It can't work that way. Complete explanation in this github issue. Also, your ng-repeat refreshes each time you change the input value. That's why you are loosing focus.

Always bind to objects:

HTML:

<td ng-repeat="f in foo">
  <input ng-model="f.value" style="width:60px" />
</td>

Controller:

function ctrl($scope) {
  $scope.foo = [];
    for (var i=0; i<5; i++) {
        $scope.foo.push({value: ''});
    }
}
Stewie
  • 60,366
  • 20
  • 146
  • 113
  • Is this related to primitive being immutable and object references? – plus- Mar 12 '13 at 22:05
  • @plus-, the primitive is mutable. It works this way because of the way JavaScript [prototypal inheritance](http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482) works with Angular scopes. – Mark Rajcok Mar 12 '13 at 22:16
1

If you don't mind using HTML5 you can use the autofocus attribute. Just add it to the input field.

<li ng-repeat="i in items">{{i.name}} <input ng-model="i.description" autofocus></li>

Here's a fork of your jsFiddle.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184