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>
Try it Yourself »
バインディングは、両方の道を進みます。ユーザが入力フィールド内の値を変更すると、 AngularJS プロパティの値も変ります:
<div ng-app="myApp" ng-controller="myCtrl">
Name:
<input ng-model="name">
<h1>You entered: {{name}}</h1>
</div>
Try it Yourself »
ng-model
ディレクティブは、アプリケーションデータ(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>
Try it Yourself »
上の例では、ng-show
属性内の式が true
を返す場合(e-mail以外の場合)にのみ span が表示されます。
ng-model 属性内にプロパティが存在しない場合、AngularJS はそれを作成します。 |
ng-model
ディレクティブは、アプリケーションデータのステータス(invalid、
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>
Try it Yourself »
ng-model
ディレクティブは、その状態に応じて HTML 要素の CSS クラスを提供します:
<style>
input.ng-invalid {
background-color:
lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
Enter your name:
<input name="myAddress" ng-model="text" required>
</form>
Try it Yourself »
ng-model
ディレクティブは、フォームフィールドのステータスに応じて、以下のクラスを追加/削除します: