3

I am running this simple code with angularjs :

HTML :

<div ng-app ng-controller="AController">
    <code>{{ itemsInArray }}</code>
    <div ng-repeat="item in itemsInArray">
        <input ng-model="itemsInArray[$index]" />
    </div>
</div>

JavaScript :

function AController($scope) {
    $scope.itemsInArray = ["strA", "strB", "strC"];
}

Binding appears to be working correctly when indexing into the array but after entering one character the input loses focus.
You can find the working code here on this fiddle : http://jsfiddle.net/QygW8/

1
  • You are facing problem because you are binding to primitive types and instead you should use object notation due to prototypical inheritance nature of javascript Commented Feb 17, 2014 at 12:53

3 Answers 3

3

I think this is happening because you are manipulating the same item which is iterated over ng-repeat. So ng-repeat sees a change in the item and re-runs the `ng-repeat which regenerates the items.

If you look at your fiddle html, you may notice this effect.

To make it work, one way you can do this

http://jsfiddle.net/cmyworld/CvLBS/

where you change your array to object array

$scope.itemsInArray = [{data:"strA"}, {data:"strB"}, {data:"strC"}];

and then bind to item.data

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

Comments

0

Try to change the model:

<div ng-repeat="item in itemsInArray">
    <input ng-model="item" />
</div>

1 Comment

The binding will be stopped
0

Even am an newbie to the angularjs, up-to my findings ng-repeat updates/repeats and recreates the whole HTML elements when there is an change in the model. Hence when a single character added to model causes ng-repeat to react and creates the all the HTML elements again which results to losing the focus.

This is an fiddle , In which u will be able to observer the changes with the model inside the ng-repeat and outside the ng-repeat.

Sorry i don't have the solution, Hope using ng-change apart of ng-model may help.

Comments

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.