?
This document uses PHP Chinese website manual Release
ngModel
指令使用NgModelController綁定一個(gè) input
,select
, textarea
(或自定義表單控件) 到域上的一個(gè)屬性。
ngModel
職責(zé)為:
input
, textarea
或select
等指令。ng-valid
, ng-invalid
, ng-dirty
, ng-pristine
, ng-touched
, ng-untouched
) ,包括動(dòng)畫。注意: ngModel
會嘗試使用表達(dá)式的計(jì)算結(jié)果來綁定到當(dāng)前域上的屬性。如果屬性在當(dāng)前域上不存在,它會立即創(chuàng)建并添加到當(dāng)前域。
使用 ngModel
的最佳實(shí)踐參見:
如何使用ngModel
的一些簡單例子參見:
以下CSS類會被添加或移除到相關(guān)聯(lián)的input/select/textarea元素上,這取決于模型的變化。
ng-valid
模型有效時(shí)設(shè)置。ng-invalid
模型無效時(shí)設(shè)置。ng-pristine
模型純凈(未變化)時(shí)設(shè)置。ng-dirty
模型臟(有變化)時(shí)設(shè)置。記住, ngAnimate可以檢測到每個(gè)類的添加和刪除。
模型的動(dòng)畫會被觸發(fā),當(dāng)綁定到模型上的輸入元素關(guān)聯(lián)的CSS樣式被添加或刪除時(shí)。這些類有: .ng-pristine
, .ng-dirty
, .ng-invalid
和 .ng-valid
,以及對模型本身進(jìn)行的任何其他驗(yàn)證。ngModel觸發(fā)的動(dòng)畫類似于ngClass上的工作方式,動(dòng)畫可以使用CSS的過渡、關(guān)鍵幀,以及JS動(dòng)畫。
下面的例子簡單演示了使用CSS過渡來渲染輸入元素上的樣式,當(dāng)它從有效變成無效時(shí):
//be sure to include ngAnimate as a module to hook into more //advanced animations .my-input { transition:0.5s linear all; background: white; } .my-input.ng-invalid { background: red; color:white; }
<input>
...
</input>
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', Function($scope) {
$scope.val = '1';
}]);
</script>
<style>
.my-input {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-input.ng-invalid {
color:white;
background: red;
}
</style>
Update input to see transitions when valid/invalid.
Integer is a valid value.
<form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
</form>
有時(shí)候綁定 ngModel
到一個(gè)getter/setter函數(shù)時(shí)很有用的。getter是一種能返回一個(gè)模型表示的無參函數(shù),setter是只有一個(gè)參數(shù)的用于設(shè)置模型內(nèi)部狀態(tài)的函數(shù)。 它對于模型內(nèi)部與視圖顯示時(shí)所用的數(shù)據(jù)形式不一致時(shí)非常有用。
要使用它,你需要添加 ng-model-options="{ getterSetter: true }"
到一個(gè)有 ng-model
元素上。你也可以添加 ng-model-options="{ getterSetter: true }"
到 <form>
上,使的表單中的所有<input>
都生效。參見 ngModelOptions
獲取更多信息。
下面的例子演示如何通過getter/setter使用 ngModel
:
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input Type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre></div>
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', Function($scope) {
var _name = 'Brian';
$scope.user = {
name: Function (newName) {
if (angular.isDefined(newName)) {
_name = newName;
}
return _name;
}
};
}]);