【问题标题】:Prevent input being updated from ng-model whilst editing防止在编辑时从 ng-model 更新输入
【发布时间】:2016-08-03 22:03:39
【问题描述】:

我的model.field 可以通过用户在输入元素中键入来修改,也可以通过后台的一些其他功能来修改。当用户在输入中键入更改时,我想忽略这些后台函数对模型所做的任何更改。例如:

$scope.model = {
    field: 'val1'
}

html

<input ng-model="model.field" ...>

IE:

  • model.field 的值为 'val1'
  • 用户开始编辑输入(它处于活动状态)
  • 模型通过其他方式更改为“val2”
  • 新值未显示在输入中 - 它仍然显示“val1”
  • 用户下一次击键(将 1 更改为 A)会覆盖 model.field 中的任何内容。
  • model.field 现在的值为 'valA'

【问题讨论】:

  • 什么在改变价值?如果它是本地的,那么您可以使用ng-change 作为触发器将本地标志设置为true,并使用ng-blur 作为触发器设置false。在更新字段之前检查此标志的状态。如果它是远程的(两个用户编辑相同的记录?),那么您必须在您的服务器或数据库(或其他)中实现某种类型的记录锁定逻辑。
  • 我同意 Lex 建议的方法,您也可以绕过 ngForm API 来检查用户是否正在积极编辑。这是一个非常hacky的例子plnkr.co/edit/lFbcmjCUcvn68nRPbkPf?p=preview
  • 我正在考虑扩展 ng-model 以关闭 2 向绑定,直到 ng-blur 事件触发:github.com/Plippe/extends-ng-model

标签: javascript angularjs binding


【解决方案1】:

添加一个 $formatter 在元素具有焦点时忽略模型似乎效果很好:

angular.module('myApp').directive('ngModelIgnoreWhenActive', function() {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function(scope, element, attributes, ngModelCtrl) {

            //Track if the element has focus. 
            //True when the user is typing into the field; false otherwise
            scope.hasFocus = false; 
            element.on('focus', function(event) {
                scope.hasFocus = true;
            });
            element.on('blur', function(event) {
                scope.hasFocus = false;
            });

            //Formats value before shown in view
            // If the element has focus, keep it's existing value
            var myFormatter = function(newValue) {
                return scope.hasFocus && element && element[0] ? element[0].value : newValue;
            }

            ngModelCtrl.$formatters.push(myFormatter);
        }
    };
});

然后将指令添加到任何相关输入:

<input ng-model="model.field" ng-model-ignore-when-active>

基于此处显示的 extends-ng-model 时间戳格式化程序的代码:https://github.com/Plippe/extends-ng-model/blob/master/src/extends-ng-model/ng-model-formatter-parser/ng-model-timestamp.js

【讨论】:

    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 2017-11-09
    相关资源
    最近更新 更多