我的model.field
可以通过用户输入输入元素来修改,也可以通过后台的其他功能进行修改。当用户在输入中键入更改时,我想忽略这些后台函数对模型所做的任何更改。例如:
$scope.model = {
field: 'val1'
}
HTML
<input ng-model="model.field" ...>
IE:
答案 0 :(得分:0)
在元素具有焦点时添加忽略模型的$ 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