Javascript 插入时更改输入值的角度指令
我想使用cutom指令更改用户输入和模型,如:Javascript 插入时更改输入值的角度指令,javascript,html,angularjs,Javascript,Html,Angularjs,我想使用cutom指令更改用户输入和模型,如: app.directive('changeInput', function ($parse) { return { require: 'ngModel', link: function (scope, elm, attrs, ctrl) { //insert logic here }); } }; }); 因此,用户在任何时候都会在中插
app.directive('changeInput', function ($parse) {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
//insert logic here
});
}
};
});
因此,用户在任何时候都会在中插入字符:
<input
name="inputText"
type="text"
change-input
data-ng-model="data.name"
>
例如,输入将从“a”更改为“b”。
我只需要更改的正确逻辑,我曾尝试使用$event
和preventDefault()
但它产生了更多的问题
谢谢。您可以使用ngModel的内置解析器和格式化程序 当检测到模型更改时,格式化程序和解析器将启动。将数据从模型更改为视图的格式化程序和将数据从视图更改为模型的解析器
app.directive('changeInput', function() {
return { restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
if(ngModel) { // Don't do anything unless we have a model
ngModel.$parsers.push(function (value) {
//value is a
// 'value' should be your model property
ngModel.$setValidity('value', true);
// sets viewValue
ngModel.$setViewValue(value);
// renders the input with the new viewValue
ngModel.$render()
return "b" // you are changing it to b. so now in your controller the value is b and you can trigger your save function
});
ngModel.$formatters.push(function (value) {
//value is b
return "a" // you are changing it to a. So now in your view it will be changed to a
});
}
}
};
});
不清楚你在问什么。如果输入从“a”更改为“b”,会发生什么?如何使用指令将用户输入从a更改为b。将出现用户插入a但插入b。很好,但如果我要更改字符串输入。@ItsikMauyhas我已更新我的答案如果您需要更具体的内容,请向我提供更多信息HI,视图不会在$parsers块中更新,有办法吗?@ItsikMauyhas现在就试试吧我修改了代码这意味着一个摘要周期已经开始了