我只想以某种方式验证项目中的文本框,以使用户不能输入字符以外的任何值。
笑话?方式,$ watch控制器中的ng-model:
<input type="text" ng-model="myText">
控制器:
$scope.$watch('myText', function() {
// put logic to strip out all non-character characters here
if ($scope.myText ... regex to look for ... ) {
// strip out the non-characters
}
})
最佳方式,在指令中使用$ parser。我不会重复@ pkozlowski.opensource提供的已经很好的答案,所以这里是链接:https://stackoverflow.com/a/14425022/215945
不要尝试使用ng-change -会引起问题。参见AngularJS - reset of $scope.value doesn't change value in template (random behavior)
更新:ng-pattern也可以用来定义正则表达式,以限制字段中允许的内容。另请参阅"cookbook" page about forms。