【发布时间】:2013-02-02 18:54:16
【问题描述】:
我只想在我的项目中验证文本框,以便用户无法输入字符以外的任何值。
【问题讨论】:
标签: javascript angularjs angularjs-directive
我只想在我的项目中验证文本框,以便用户无法输入字符以外的任何值。
【问题讨论】:
标签: javascript angularjs angularjs-directive
骇客?方式,$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。
【讨论】: