如果输入字段的ng-pattern与正则表达式不匹配,我想禁用带有ng-disable的按钮。在这种情况下,正则表达式为“[0-9]”。我尝试了以下代码:
的index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml" ng-app="Filter">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ASCII" />
<title>Test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script type="text/javascript" src="Test.js"></script>
</head>
<body>
<div class="ctrl" ng-controller="Ctrl">
Text <input type="text" ng-model="input_field" ng-pattern="[0-9]"><br/>
<button ng-disabled="input_field.$valid">Start Filter</button>
</div>
</body>
</html>
Test.js
Module.controller('Ctrl', function($scope){
$scope.input_field = "Insert your Text here!";
}
不幸的是它不起作用。我尝试了很多方法,但没有任何效果。如果模式不匹配,您对如何禁用按钮有任何想法。
答案 0 :(得分:2)
我认为你应该用<form>
包装它并修复语法:$error
而不是$valid
,[0-9]
- &gt; /^[0-9]/
。这是一个演示,适当调整:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
Input: <input type="text" ng-model="input_field" name="input_field" ng-pattern="/^[0-9]/" placeholder="Insert a number"><br/>
<button ng-disabled="myForm.input_field.$error.pattern || !input_field">Start Filter</button>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {});
</script>
</body>
</html>
&#13;