[英]ng-disable a button if ng-pattern of input does not match
I want to disable a button with ng-disable if ng-pattern of an input field does not match the regular expression. 如果输入字段的ng-pattern与正则表达式不匹配,我想用ng-disable禁用按钮。 In this case the regular expression is "[0-9]". 在这种情况下,正则表达式为“ [0-9]”。 I have tried the following code: 我尝试了以下代码:
Index.html 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 Test.js
Module.controller('Ctrl', function($scope){
$scope.input_field = "Insert your Text here!";
}
Unfortunately it is not working. 不幸的是,它不起作用。 I have tried many ways but nothing worked. 我尝试了很多方法,但是没有任何效果。 Do you have any ideas how to disable the button if the pattern do not match. 您是否有任何想法,如果模式不匹配,如何禁用按钮。
I think you should wrap it with <form>
and fix the syntax: $error
instead of $valid
, [0-9]
-> /^[0-9]/
. 我认为您应该用<form>
包装它并修复语法: $error
而不是$valid
, [0-9]
-> /^[0-9]/
。 Here is a demo, adjust it appropriately: 这是一个演示,请对其进行适当调整:
<!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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.