IT

AngularJS #6 - ng-model Directive

금마s 2021. 12. 19. 23:28

✔ AngularJS ng-model Directive

 > binds the value of HTML controls (input, select textarea) to application data.

 

1. The ng-model Directive

 > with 'ng-model' you can bind the value of an input field to a variable created in AngularJS

<div ng-app="myApp" ng-controller="myCtrl">
 Name: <input ng-model="name">
</div>

<script>
 var app = angular.model('myApp', []);
 app.controller('myCtrl', function($scope) {
  $scope.name = "John Doe";
 });
</script>

 

2. Two-way Binding

 > binding goes both ways. If the user changes the value insdie the input field, the AngularJS property will also change its value

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

 

3. Validate User Input

 > 'ng-model' directive can provide type validation for application data (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">Not a valid e-mail address</span>
</form>

: the span will be displayed only if the expression in the 'ng-show' attribute returns true

 !! If the property in the 'ng-model' attribute does not exist, AngularJS will create one for you

 

4. Application Status

 > 'ng-model' directive provide status for application data (valid, dirty, touched, error)

<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>

 

5. CSS Classes

 > 'ng-model' directive provides CSS classes for HTML elements, depending on their status

<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' directive adds/removes the following classes, according to the status of the form field

  - ng-empty

  - ng-not-empty

  - ng-touched

  - ng-untouched

  - ng-valid

  - ng-invalid

  - ng-dirty

  - ng-pending

  - ng-pristine

 

 

 

 

 

 

728x90

'IT' 카테고리의 다른 글

AngularJS #8 - Controllers  (0) 2021.12.21
AngularJS #7 - Data Binding  (0) 2021.12.21
AngularJS #5 - Directives  (0) 2021.12.18
AngularJS #4 - Modules  (0) 2021.12.18
VS CODE 다운로드  (0) 2021.01.28