Bound Input gets unfocused in angularjs

旧城冷巷雨未停 提交于 2019-12-05 02:44:31

问题


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:


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




回答2:


Try to change the model:

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



回答3:


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.



来源:https://stackoverflow.com/questions/21829175/bound-input-gets-unfocused-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!