Chỉ thị ng-model trói giá trị các điều khiển HTML (input, select, textarea) với dữ liệu ứng dụng
Chỉ thị ng-model
Với chỉ thị này, bạn có thể trói giá trị của 1 trường nhập liệu (input) với 1 biến được tạo trang AngularJS.
<div ng-app="myApp" ng-controller="myCtrl"> Tên: <input ng-model="name"> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.name = "dammio.com"; }); </script>
Trói 2 chiều
Cách trói này dùng cho 2 chiều. Nếu người dùng thay đổi giá trị bên trong trường nhập liệu thì thuộc tính AngularJS cũng thay đổi giá trị.
<div ng-app="myApp" ng-controller="myCtrl"> Tên: <input ng-model="name"> <h1>Bạn đã nhập tên: {{name}}</h1> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.name = "dammio.com"; }); </script>
Chứng thực User Input
Chỉ thị ng-model cung cấp dạng chứng thực dữ liệu ứng dụng (number, e-mail, required):
<form ng-app="" name="myForm"> Email: <input type="email" name="myAddress" ng-model="text"> <span ng-show="myForm.myAddress.$error.email">Địa chỉ email chưa đúng định dạng</span> </form>
Trong ví dụ trên, nếu người dùng nhập sai định dạng email thì diễn giải trong thuộc tính ng-show trả về true, vì vậy sẽ xuất hiện thông báo lỗi nhập sai định dạng email. Nếu thuộc tính ở ng-model không tồn tại thì AngularJS sẽ tự động tạo.
Tình trạng ứng dụng
Chỉ thị ng-model cung cấp tình trạng cho ứng dụng dữ liệu (invalid, dirty, touched, error):
<form ng-app="" name="myForm" ng-init="myText = '[email protected]'"> Email: <input type="email" name="myAddress" ng-model="myText" required> <h1>Status</h1> {{myForm.myAddress.$valid}} {{myForm.myAddress.$dirty}} {{myForm.myAddress.$touched}} </form>
Các lớp CSS
Chỉ thị ng-model cung cấp các lớp CSS cho các phần tử HTML, tùy theo tình trạng của chúng.
<style> input.ng-invalid { background-color: lightblue; } </style> <body> <form ng-app="" name="myForm"> Nhập tên của bạn - dammio.com: <input name="myName" ng-model="myText" required> </form>
Chỉ thị ng-model thêm/bớt các lớp sau, theo tình trạng của trường form: ng-empty, ng-not-empty, ng-touched, ng-untouched, ng-valid, ng-invalid, ng-dirty, ng-pending và ng-pristine.
- APA:
Dammio. (2017). [AngularJS] Phần 5: Mô hình trong AngularJS. https://www.dammio.com/2017/02/19/angularjs-phan-5-mo-hinh-trong-angularjs.
- BibTeX:
@misc{dammio,
author = {Dammio},
title = {[AngularJS] Phần 5: Mô hình trong AngularJS},
year = {2017},
url = {https://www.dammio.com/2017/02/19/angularjs-phan-5-mo-hinh-trong-angularjs},
urldate = {2025-01-09}
}