onkeypress()未调用函数



我有一项任务不让用户键入"%"在一个文本区域,因此我做了这个

但一旦我点击文本区域,我仍然可以键入"%"。。。这意味着onkeypress无法识别我的函数,或者函数本身是错误的。

$scope.test = function() {
var txtarea = document.getElementById("exampleFormControlTextarea1");
txtarea.addEventListener("input", function() {
txtarea.value = txtarea.value.replaceAll("%", "");
})
}

我也尝试过这种方式:

function myfunction () {
var txtarea = document.getElementById("exampleFormControlTextarea1");
txtarea.addEventListener("input", function() {
txtarea.value = txtarea.value.replaceAll("%", "");
})
}
<div class="col-md-12 label-base">
<label for="exampleFormControlTextarea1">Justify</label>
<textarea style="resize: none" ng-disabled="negociacaoEspecCtrl.proposta.flagDesabilitaEdicaoProposta" 
class="form-control observacoes" id="exampleFormControlTextarea1" rows="3" 
ng-model="negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial"
onkeypress="test()"></textarea>
</div>

我相信你要找的是ngKeypress here

你可以这样在ngKeypress上调用你的函数。我冒昧地将你的ng模型对象重命名为这里的模型,因为你的对象太长了

<div class="col-md-12 label-base">
<label for="exampleFormControlTextarea1">Justify</label>
<textarea style="resize: none" ng-disabled="negociacaoEspecCtrl.proposta.flagDesabilitaEdicaoProposta" 
class="form-control observacoes" id="exampleFormControlTextarea1" rows="3" 
ng-model="model"
ng-keypress="test()"></textarea>
</div>

由于你的文本区域有一个ng模型,你应该把你的方法改为这个

$scope.test = function() {
console.log("Method called");
$scope.model = $scope.model.replaceAll("%", "");
}

来自这篇文章:https://stackoverflow.com/a/35777284/1772933

将过滤器与ng更改功能一起使用,例如:

angular.module("test", [])
.filter("purger", function() {
return function(input) {
return input.replace(/%/gi, "");
}
}).controller("testController", function($scope, purgerFilter) {
$scope.onChange = function() {
$scope.negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial = purgerFilter($scope.negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial);
}
})

和你的元素:

<textarea ... 
ng-model="negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial"
ng-change="onChange()"></textarea>

最新更新