简体   繁体   English

AngularJS数据绑定破坏了ngRepeat +奇怪的行为

[英]AngularJS Data Binding Breaks ngRepeat + Strange Behavior

Background : I'm a systems guy who switched to Front End development. 背景 :我是一名系统人员,改用前端开发。 Just dorking around with Angular. 只是和Angular呆在一起。 Got creative with data binding and now I'm trying to understand this behavior: 具有数据绑定的创意,现在我试图了解这种行为:

<div ng-app>
    <div class="container">Name
        <input type="text" ng-model="user.name">
    </div>{{ user.name }}
    <div class="container">Name
        <input type="text" ng-model="user.name">
    </div>
    <ul ng-model="user.name">
        <li ng-repeat="l in user.name">{{ l }}</li>
    </ul>
</div>

http://jsfiddle.net/Lpm74dd8/ http://jsfiddle.net/Lpm74dd8/

I would expect this to take my input from either box, mirror the text between the input boxes, and repeat each letter on its own line at the bottom. 我希望这能使我从任何一个框输入内容,在输入框之间镜像文本,并在底部的每行重复每个字母。

If I type "test" in one of the inputs, ng-repeat will break when a letter repeats. 如果我在其中一个输入中输入“ test”,则重复字母时ng-repeat会中断。

Typing the alphabet sequentially works as I expect. 按我的预期顺序输入字母是可以的。

Why does ng-repeat break when input letters are duplicated? 输入字母重复时,为什么ng-repeat会中断? I have no practical use for this, I was just experimenting with Angular for fun and came across this and don't understand it. 我对此没有任何实际用途,我只是在尝试Angular的乐趣,偶然发现了这一点,并不了解。

ng-repeat will not accept duplicate entries. ng-repeat将不接受重复的条目。 As test has t as duplicate entry, it will fail. 由于testt的重复条目,它就会失败。

Add track by expression to avoid this. track by表达式添加track by可避免这种情况。

When we do not provide any track by expression the entry(in this case each letter) itself is treated as a unique identifier to link the entry to the list to track the changes in it. 当我们不track by表达式提供任何track by该条目(在本例中为每个字母)本身被视为唯一标识符,以将该条目链接到列表以跟踪列表中的更改。

<li ng-repeat="l in user.name track by $index">{{ l }}</li>

Use track by $index with ng-repeat for dupilcate entries in array. track by $index与ng-repeat一起用于数组中的重复项。 Try this fiddle http://jsfiddle.net/1Lw11bqr/ 试试这个小提琴http://jsfiddle.net/1Lw11bqr/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM