AngularJS ng-model สั่งออก

ng-model คำสั่งจะมอบค่าจากควบคุม HTML (input, select, textarea) ไปยังข้อมูลในโปรแกรม.

คำสั่ง ng-model

ใช้ ng-model คำสั่ง คุณสามารถจับค่าจากช่องกรอกที่เปิดใช้งานและมอบให้เป็นค่าที่สร้างใน AngularJS:

ตัวอย่าง

<div ng-app="myApp" ng-controller="myCtrl">
  Name: <input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.name = "Bill Gates";
});
</script>

ทดลองด้วยตัวเอง

การบอกตัวเป็นทางที่สอง

การบอกตัวเป็นทางที่สองของเรื่อง ถ้าผู้ใช้เปลี่ยนค่าในช่องกรอกข้อมูล คุณสมบัติของ AngularJS จะเปลี่ยนค่าเช่นกัน:

ตัวอย่าง

<div ng-app="myApp" ng-controller="myCtrl">
  Name: <input ng-model="name">
  <h1>You entered: {{name}}</h1>
</div>

ทดลองด้วยตัวเอง

ตรวจสอบการใส่ข้อมูลผู้ใช้

ng-model คำสั่งสามารถตรวจสอบรูปแบบข้อมูลของข้อมูลในโปรแกรม (ตัวเลข, อีเมล, ต้องกรอก):

ตัวอย่าง

<form ng-app="" name="myForm">
  Email:
  <input type="email" name="myAddress" ng-model="text">
  <span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span>
</form>

ทดลองด้วยตัวเอง

ในตัวอย่างดังกล่าว มีเพียงแบบที่: ng-show คุณสมบัติภายในความหมายความหลายแสดง: true จะแสดง span ขึ้นมา:

ถ้า ng-model คุณสมบัติภายในคุณสมบัติไม่มีอยู่ และ AngularJS จะสร้างคุณสมบัติให้คุณ:

สถานะโปรแกรม

ng-model คำสั่งสามารถเสนอสถานะของข้อมูลในโปรแกรม (มีความถูกต้อง, มีความเสื่อม, มีการที่จับเงิน, ข้อผิดพลาด):

ตัวอย่าง

<form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'">
  Email:
  <input type="email" name="myAddress" ng-model="myText" required>
  <h1>Status</h1>
  {{myForm.myAddress.$valid}}
  {{myForm.myAddress.$dirty}}
  {{myForm.myAddress.$touched}}
</form>

ทดลองด้วยตัวเอง

หลัก CSS

ng-model คำสั่งเพื่อให้ CSS หลักคัดกรองตามสถานะของ HTML อิเล็ม:

ตัวอย่าง

<style>
input.ng-invalid {
  background-color: lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
  Enter your name:
  <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