Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

AngularJS ng-model 指令


ng-model 指令将 HTML 控件(input、select、textarea)的值绑定到应用程序数据。


ng-model 指令

使用 ng-model 指令,您可以将输入字段的值绑定到在 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>
亲自试一试 »

双向绑定

绑定是双向的。如果用户更改输入字段中的值,AngularJS 属性也会更改其值。

示例

<div ng-app="myApp" ng-controller="myCtrl">
  姓名: <input ng-model="name">
  <h1>您输入了: {{name}}</h1>
</div>
亲自试一试 »


验证用户输入

ng-model 指令可以为应用程序数据提供类型验证(数字、电子邮件、必填)

示例

<form ng-app="" name="myForm">
  电子邮件
  <input type="email" name="myAddress" ng-model="text">
  <span ng-show="myForm.myAddress.$error.email">无效的电子邮件地址</span>
</form>
亲自试一试 »

在上面的示例中,只有当 ng-show 属性中的表达式返回 true 时,才会显示 span。

如果 ng-model 属性中的属性不存在,AngularJS 将为您创建一个。


应用程序状态

ng-model 指令可以为应用程序数据提供状态(有效、脏、已触碰、错误)

示例

<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">
  电子邮件
  <input type="email" name="myAddress" ng-model="myText" required>
  <h1>状态</h1>
  {{myForm.myAddress.$valid}}
  {{myForm.myAddress.$dirty}}
  {{myForm.myAddress.$touched}}
</form>
亲自试一试 »

CSS 类

ng-model 指令根据 HTML 元素的状态提供 CSS 类。

示例

<style>
input.ng-invalid {
  background-color: lightblue;
}
</style>
<body>

<form ng-app="" name="myForm">
  输入您的姓名
  <input name="myName" ng-model="myText" required>
</form>
亲自试一试 »

ng-model 指令根据表单字段的状态添加/删除以下类

  • ng-empty
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid
  • ng-invalid
  • ng-dirty
  • ng-pending
  • ng-pristine

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.