AngularJS中的ng-required指令用於指定HTML元素的必需屬性。僅當ng-required指令中的表達式返回true時,才需要表單中的輸入字段。 <input>,<select>和<textarea>支持。
用法:
<element ng-required="expression"> Contents... </element>
範例1:本示例使用ng-required指令將表單標簽的輸入文本字段設置為必填。
<!DOCTYPE html>
<html>
<head>
<title>ng-required Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
<style>
.req {
font-size:90%;
font-style:italic;
color:red;
}
</style>
</head>
<body style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h2>ng-required Directive</h2>
<div ng-app="app" ng-controller="myCtrl">
<form name="myForm">
<p>Enter Your Name:<br/>
<span>
<input type="text" name="name"
ng-model="Name" ng-required ="true" />
</span>
</p>
<span ng-show="myForm.name.$invalid" class="req">
This is the required field.
</span>
</form>
</div>
<script>
var app = angular.module("app", []);
app.controller("myCtrl", function($scope) {
$scope.Name = "";
});
</script>
</body>
</html>
輸出:
輸入名稱之前:
輸入名稱後:
範例2:本示例使用ng-required指令在選中複選框後創建必填字段。
<!DOCTYPE html>
<html>
<head>
<title>ng-required Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
</head>
<body ng-app="app"style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h2>ng-required Directive</h2>
<div ng-controller="geek" style="font-family:arial;">
<form name="myform">
<label for="requiredValue">
Is Required:
</label>
<input type="checkbox" ng-model="requiredValue"
id="required" />
<br><br>
<label for="input">Enter Name:</label>
<input type="text" ng-model="model" id="input"
name="input" ng-required="requiredValue" />
<br>
<p style="color:red;"
ng-show='myform.input.$error.required'>
Name is required
</p>
</form>
</div>
<script>
var app = angular.module('app', [])
app.controller('geek', ['$scope', function($scope) {
$scope.requiredValue = true;
}]);
</script>
</body>
</html>
輸出:
在選中複選框之前:
選中複選框後:
相關用法
- AngularJS ng-if用法及代碼示例
- AngularJS ng-cut用法及代碼示例
- AngularJS ng-value用法及代碼示例
- AngularJS ng-src用法及代碼示例
- AngularJS ng-app用法及代碼示例
- AngularJS ng-csp用法及代碼示例
- AngularJS ng-jq用法及代碼示例
- AngularJS ng-bind用法及代碼示例
- AngularJS ng-srcset用法及代碼示例
- AngularJS ng-paste用法及代碼示例
- AngularJS ng-submit用法及代碼示例
- AngularJS ng-style用法及代碼示例
- AngularJS ng-selected用法及代碼示例
注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 AngularJS | ng-required Directive。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。