Bound Input gets unfocused in angularjs

2019-03-31 23:33发布

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/

3条回答
一夜七次
2楼-- · 2019-04-01 00:00

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

查看更多
该账号已被封号
3楼-- · 2019-04-01 00:01

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.

查看更多
你好瞎i
4楼-- · 2019-04-01 00:05

Try to change the model:

<div ng-repeat="item in itemsInArray">
    <input ng-model="item" />
</div>
查看更多
登录 后发表回答