©
Dieses Dokument verwendetPHP-Handbuch für chinesische WebsitesFreigeben
ngModel
指令使用NgModelController绑定一个input
,select
,textarea
(或自定义表单控件) 到域上的一个属性。
ngModel
职责为:
input
,textarea
或select
等指令。ng-valid
,ng-invalid
,ng-dirty
,ng-pristine
,ng-touched
,ng-untouched
) ,包括动画。注意:ngModel
会尝试使用表达式的计算结果来绑定到当前域上的属性。如果属性在当前域上不存在,它会立即创建并添加到当前域。
使用ngModel
的最佳实践参见:
如何使用ngModel
的一些简单例子参见:
以下CSS类会被添加或移除到相关联的input/select/textarea元素上,这取决于模型的变化。
ng-valid
模型有效时设置。ng-invalid
模型无效时设置。ng-pristine
模型纯净(未变化)时设置。ng-dirty
模型脏(有变化)时设置。记住, ngAnimate可以检测到每个类的添加和删除。
模型的动画会被触发,当绑定到模型上的输入元素关联的CSS样式被添加或删除时。这些类有:.ng-pristine
,.ng-dirty
,.ng-invalid
和.ng-valid
,以及对模型本身进行的任何其他验证。ngModel触发的动画类似于ngClass上的工作方式,动画可以使用CSS的过渡、关键帧,以及JS动画。
下面的例子简单演示了使用CSS过渡来渲染输入元素上的样式,当它从有效变成无效时:
//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; }
...
angular.module('inputExample',[]).controller('ExampleController',['$scope',Function($scope){$scope.val='1';}]);.my-input{-webkit-transition:all linear0.5s;transition:all linear0.5s;background:transparent;}.my-input.ng-invalid{color:white;background:red;}Update input to see transitions when valid/invalid. Integer is a valid value.
有时候绑定ngModel
到一个getter/setter函数时很有用的。getter是一种能返回一个模型表示的无参函数,setter是只有一个参数的用于设置模型内部状态的函数。 它对于模型内部与视图显示时所用的数据形式不一致时非常有用。
要使用它,你需要添加ng-model-options="{ getterSetter: true }"
到一个有ng-model
元素上。你也可以添加ng-model-options="{ getterSetter: true }"
到上,使的表单中的所有
都生效。参见
ngModelOptions
获取更多信息。
下面的例子演示如何通过getter/setter使用ngModel
:
ng-controller="ExampleController">user.name =ng-bind="user.name()">
angular.module('getterSetterExample',[]).controller('ExampleController',['$scope',Function($scope){var_name='Brian';$scope.user={name:Function(newName){if(angular.isDefined(newName)){_name=newName;}return_name;}};}]);