簡體   English   中英

ng-repeat中的角NgModelController行為

[英]Angular NgModelController behaviour inside ng-repeat

一旦我意識到ng-model指令的工作原理並且對它的行為絕對有信心,這個例子就讓我大吃一驚

<html ng-app>
<head>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body ng-init="names = ['Sam', 'Harry', 'Sally']">
    <h1>Fun with Fields and ngModel</h1>
    <p>names: {{names}}</p>
    <h3>Binding to each element directly:</h3>
    <div ng-repeat="name in names">
        Value: {{name}}
        <input ng-model="name">                         
    </div>
    <p class="muted">The binding does not appear to be working: the value in the model is not changed.</p>
    <h3>Indexing into the array:</h3>
    <div ng-repeat="name in names">
        Value: {{names[$index]}}
        <input ng-model="names[$index]">                         
    </div>
    <p class="muted">Type one character, and the input field loses focus. However, the binding appears to be working correctly.</p>
</body>

ng-repeat小提琴 主要問題是三個不同版本的angular的行為。 我知道ng-repeat會為每個數組項創建一個新作用域,我想(不確定)它僅跟蹤數組引用及其大小(因此,數組項不會在更改時引起$ digest循環),但是,我們ve到達這里(僅觀看不帶$ index的第一個示例):對於版本1.0.3 <我們已經預期的行為:用輸入更改'name'屬性只會更改ngModelController的值(作用域繼承),這很公平,1.1.1-好吧,這是怎么回事:我們甚至沒有在輸入中獲取新值,而且! 我們不會重新渲染項目,因為我們不會失去焦點(而且我真的不明白為什么$ digest循環會像Artem 所說的那樣觸發此輸入的值替換),第三版-1.2.1:也更改輸入值更改外部作用域中的“名稱”值(據我所知ngModelController應該繼承由ng-repeat指令創建的作用域)。 那么,在所有三個示例中到底發生了什么(為什么)?

使用Angular最新版本(1.2.1)並按$ index進行跟蹤。 此問題已解決

http://jsfiddle.net/rnw3u/55/

    <div ng-repeat="name in names track by $index">
        Value: {{names[$index]}}
        <input ng-model="names[$index]">                         
    </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM