AngularJS 模型
-
ng-model 指令
ng-model
指令将HTML控件的值(input, select, textarea)绑定到应用程序数据。使用ng-model
指令,您可以将输入字段的值绑定到在AngularJS中创建的变量。<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>蝴蝶教程(jc2182.com)</title> <script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> Name: <input type="text" ng-model="name"> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.name = "John Doe"; }); </script> </body> </html>
-
双向绑定
绑定是双向的。 如果用户在input框中输入更改值,则AngularJS属性还将更改其值:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>蝴蝶教程(jc2182.com)</title> <script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script> </head> <body> <div ng-app=""> <p>在输入框中输入内容:</p> <p>Name: <input type="text" ng-model="name"></p> <h1>hello {{ name }}</h1> </div> </body> </html>
-
验证用户输入
ng-repeat
指令可以为应用程序数据(number, e-mail, required))提供类型验证:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>蝴蝶教程(jc2182.com)</title> <script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script> </head> <body> <form ng-app="" name="myForm"> Email: <input type="email" name="myAddress" ng-model="text"> <span ng-show="myForm.myAddress.$error.email">无效的电子邮件地址</span> </form> </body> </html>
在上面的示例中,仅当ng-show
属性中的表达式返回 true 时,才会显示范围。如果
ng-model
属性中的属性不存在,AngularJS将为您创建一个。 -
应用程序数据的状态
ng-app
ng-model指令可以提供应用程序数据的状态(invalid, dirty, touched, error):<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>蝴蝶教程(jc2182.com)</title> <script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script> </head> <body> <form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'"> Email: <input type="email" name="myAddress" ng-model="myText" required> <h1>状态</h1> {{ myForm.myAddress.$valid }} {{ myForm.myAddress.$dirty }} {{ myForm.myAddress.$touched }} </form> </body> </html>
-
CSS 类
ng-model
指令根据其状态为HTML元素提供CSS类:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>蝴蝶教程(jc2182.com)</title> <script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script> <style> input.ng-invalid { background-color: lightblue; } </style> </head> <body> <form ng-app="" name="myForm"> 输入你的名字: <input name="myName" ng-model="myText" required> </form> </body> </html>
ng-model
指令根据表单字段的状态添加/删除以下类:ng-empty
ng-not-empty
ng-touched
ng-untouched
ng-valid
ng-invalid
ng-dirty
ng-pending
ng-pristine