AngularJS ng-model 指令
ng-model 指令用於綁定應用程序數據到HTML 控制器(input, select, textarea)的值。
ng-model 指令
ng-model
指令可以將輸入域的值與AngularJS創建的變量綁定。
AngularJS 實例
< div ng-app= "myApp" ng-controller= "myCtrl" >
名字: < input ng-model= "name" >
< /div >
< script >
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
< /script >
名字: < input ng-model= "name" >
< /div >
< script >
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
< /script >
嘗試一下»
雙向綁定
雙向綁定,在修改輸入域的值時, AngularJS 屬性的值也將修改:
AngularJS 實例
< div ng-app= "myApp" ng-controller= "myCtrl" >
名字: < input ng-model= "name" >
< h1 >你輸入了: {{name}} < /h1 >
< /div >
名字: < input ng-model= "name" >
< h1 >你輸入了: {{name}} < /h1 >
< /div >
嘗試一下»
驗證用戶輸入
AngularJS 實例
< form ng-app= "" name= "myForm" >
Email:
< input type= "email" name= "myAddress" ng-model= "text" >
< span ng-show= "myForm.myAddress.$error.email" >不是一個合法的郵箱地址< /span >
< /form >
Email:
< input type= "email" name= "myAddress" ng-model= "text" >
< span ng-show= "myForm.myAddress.$error.email" >不是一個合法的郵箱地址< /span >
< /form >
嘗試一下»
以上實例中,提示信息會在ng-show
屬性返回true
的情況下顯示。
應用狀態
ng-model
指令可以為應用數據提供狀態值(invalid, dirty, touched, error):
AngularJS 實例
< form ng-app= "" name= "myForm" ng-init= "myText = '[email protected]'" >
Email:
< input type= "email" name= "myAddress" ng-model= "myText" required > < /p >
< h1 >狀態< /h1 >
{{myForm.myAddress.$valid}}
{{myForm.myAddress.$dirty}}
{{myForm.myAddress.$touched}}
< /form >
Email:
< input type= "email" name= "myAddress" ng-model= "myText" required > < /p >
< h1 >狀態< /h1 >
{{myForm.myAddress.$valid}}
{{myForm.myAddress.$dirty}}
{{myForm.myAddress.$touched}}
< /form >
嘗試一下»
CSS 類
ng-model
指令基於它們的狀態為HTML元素提供了CSS類:
AngularJS 實例
< style >
input.ng-invalid {
background-color: lightblue;
}
background-color: lightblue;
}
< /style >
< body >
< form ng-app= "" name= "myForm" >
輸入你的名字:
< input name= "myAddress" ng-model= "text" required >
< /form >
< body >
< form ng-app= "" name= "myForm" >
輸入你的名字:
< input name= "myAddress" ng-model= "text" required >
< /form >
嘗試一下»
ng-model
指令根據表單域的狀態添加/移除以下類:
- ng-empty
- ng-not-empty
- ng-touched
- ng-untouched
- ng-valid
- ng-invalid
- ng-dirty
- ng-pending
- ng-pristine