AngularJS ng-model ディレクティブ


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


ng-model ディレクティブ

ng-modelディレクティブは、入力フィールドの値を AngularJS が作成した変数にバインドできます。

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 = "John Doe";
});
</script>

試してみる »

双方向バインディング

双方向バインディング:入力フィールドの値を変更すると、AngularJS プロパティの値も変更されます:

AngularJS サンプル

<div ng-app="myApp" ng-controller="myCtrl">
名前:<input ng-model="name">
    <h1>あなたの入力:{{name}}</h1>
</div>

試してみる »

ユーザー入力の検証

AngularJS サンプル

<form ng-app="" name="myForm">
    Email:
    <input type="email" name="myAddress" ng-model="text">
    <span ng-show="myForm.myAddress.$error.email">有効なメールアドレスではありません</span>
</form>

試してみる »

上記の例では、プロンプトメッセージはng-showプロパティが返すtrue場合に表示されます。


アプリケーションの状態

ng-modelディレクティブはアプリケーションデータに状態値(invalid, dirty, touched, error)を提供できます:

AngularJS サンプル

<form ng-app="" name="myForm" ng-init="myText = '[email protected]'"> Email: <input type="email" name="myAddress" ng-model="myText" required> <p>メールアドレスを編集して、状態の変化を確認してください。</p> <h1>状態</h1> <p>Valid: {{myForm.myAddress.$valid}} (入力された値が有効な場合は true です)。</p> <p>Dirty: {{myForm.myAddress.$dirty}} (値が変更された場合は true です)。</p> <p>Touched: {{myForm.myAddress.$touched}} (タップされた場合は true です)。</p>

試してみる »

CSS クラス

ng-modelディレクティブは、それらの状態に基づいて HTML 要素に CSS クラスを提供します:

AngularJS サンプル

<style>
input.ng-invalid {
    background-color: lightblue;
}
</style>
<body>

<form ng-app="" name="myForm">
あなたの名前を入力してください:
    <input name="myAddress" ng-model="text" required>
</form>

試してみる »

ng-modelディレクティブはフォームフィールドの状態に応じて次のクラスを追加/削除します:

  • ng-empty
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid
  • ng-invalid
  • ng-dirty
  • ng-pending
  • ng-pristine
その他の拡張