ng-model 指令用于绑定应用程序数据到 HTML 控制器(input, select, textarea)的值。
双向绑定
修改输入的值,AngularJS属性值也修改:
<div ng-app="myApp" ng-controller="myCtrl">
名字: <input ng-model="name">
<h1>你输入了: {{name}}</h1>
</div>
验证用户输入
<form ng-app="" name="myForm">
Email:
<input type="email" name="myAddress" ng-model="text">
<span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span>
</form>
在这里当输入的信息不是一个邮箱地址的时候,显示<span>
标签里面的内容。
应用状态
<form ng-app="" name="myForm" ng-init="myText = 'test@qq.com'">
Email:
<input type="email" name="myAddress" ng-model="myText" required>
<h1>状态</h1>
<p>Valid: {{myForm.myAddress.$valid}} (如果输入的值是合法的则为 true)。</p>
<p>Dirty: {{myForm.myAddress.$dirty}} (如果值改变则为 true)。</p>
<p>Touched: {{myForm.myAddress.$touched}} (如果通过触屏点击则为 true)。</p>
CSS类
<head>
<style>
input.ng-invalid{
background-color: lightblue;
}
</style>
</head>
<body>
<form ng-app="" name="myForm">
请输入你的名字:
<input name="myName" ng-model="myText" required>
</form>
<p>编辑文本域,颜色发生变化</p>
<p>文本域添加了required属性,该值是必须的。否则不合法!</p>
</body>
ng-model指令根据表单域的状态添加/移除以下类:
ng-empty
ng-not-empty
ng-touched
ng-untouched
ng-valid
ng-invalid
ng-dirty
ng-pending
ng-pristine