AngularJSモデルディレクティブ


ng-modelディレクティブは、HTMLコントロール(input、select、textarea)の値をアプリケーションデータにバインドします。


モデリング指令

ディレクティブを使用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 = "John Doe";
});
</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

属性のプロパティがng-model存在しない場合、AngularJSがプロパティを作成します。


アプリケーションの状態

ディレクティブは、アプリケーションデータのng-modelステータス(有効、ダーティ、タッチ、エラー)を提供できます。

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

CSSクラス

ng-modelディレクティブは、ステータスに応じて、HTML要素のCSSクラスを提供します

<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ディレクティブは、フォームフィールドのステータスに応じて、次のクラスを追加/削除します

  • の-空
  • の-空ではない
  • の-触れた
  • の-手つかず
  • of-有効
  • の-無効
  • の-汚い
  • ng-保留中
  • of-pristine