我在将用户数据输入到使用 Angular ng-repeat 显示的有序字段时遇到了一些问题。
假设您希望某些值显示在列表中,并且这些值可能是可编辑的。同时,您正在订购该数据。由于 ng-model 的工作原理和 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>';
a = $element.html(template);
$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 更新。
最佳答案
您可以使用 ng-model-options
及其 updateOn
属性,以便您的模型仅在用户离开该字段时更新。
你可以在这里看到它是如何工作的:https://docs.angularjs.org/api/ng/directive/ngModelOptions (在“触发和去抖动模型更新”部分有一个示例)
例子:
<input ng-model-options="{ updateOn: 'blur'}" />
关于javascript - 在 Angular 上编辑有序输入 ng-repeat 时避免回流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42437463/