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 = "Bill Gates";
});
</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 명령어는 애플리케이션 데이터의 상태(유효,(dirty), 터치, 오류)를 제공할 수 있습니다:

예제

<form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'">
  이메일:
  <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