2017-02-24 56 views
1

在將用戶數據輸入到使用Angular ng-repeat顯示的有序字段時,我遇到了一些問題。在編輯有序輸入ng-repeat時避免迴流

假設您希望某些值顯示在列表中,並且這些值可能是可編輯的。與此同時,您正在訂購這些數據。由於ng模型的工作原理和Angular迴流循環的原理,如果一個輸入的值在編輯時超過另一個輸入的值,您會發現自己在錯誤的字段上輸入。請看下面的例子:

var app = angular.module('app', []); 
 
app.directive('myrow', Row); 
 
app.controller('controller', Controller); 
 

 

 
function Controller() { 
 
    this.order = '-value'; 
 
    this.inputs = [ 
 
    {value: 1, tag: "Peas"}, 
 
    {value: 2, tag: "Apples"}, 
 
    {value: 3, tag: "Potatos"} 
 
    ]; 
 
} 
 
function Row($compile, $sce){ 
 
    var linker = function($scope, $element, $attrs){ 
 
    var template = '<div>- <input type="number" ng-model="data.value"><span ng-bind="data.tag"></span></div>'; 
 
\t \t a = $element.html(template); 
 
\t \t $element.html(template); 
 
    $compile($element.contents())($scope); 
 
    } 
 
    return { 
 
    restrict: 'AE', 
 
    replace: true, 
 
    scope: { 
 
     data: "=" 
 
    }, 
 
    link: linker 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="controller as ctrl"> 
 
    List: 
 
    <div ng-repeat="item in ctrl.inputs | orderBy: ctrl.order"> 
 
    <div myrow data="item"></div> 
 
    </div> 
 

 
</div>

我做了這個簡化的例子作爲原始成分有數以千計的線條和一些依賴。這裏並沒有完全重現這個問題,但是,當你編寫代碼時,有時候輸入失去了焦點,例如,當沒有編譯指令時(這在我的真實代碼中是完全必要的)不會發生。有關如何解決這個問題的任何想法?是否可以激活ng-model更新而不是用戶輸入。

回答

2

您可以使用ng-model-options及其updateOn屬性,以便僅在用戶離開該字段時更新模型。

你可以看到它是如何工作在這裏:https://docs.angularjs.org/api/ng/directive/ngModelOptions(有一個在「觸發和防抖動模式的更新」部分樣本)

例如:

<input ng-model-options="{ updateOn: 'blur'}" />