AngularJS データ・バインディング


AngularJS のデータバインディングは、モデルとビューの間を同期します。


データモデル

AngularJS アプリケーションは、通常、データ・モデルを持ってます。 データモデルは、アプリケーションのための利用できるデータの集まりです。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});

HTML ビュー

AngularJS のアプリケーションが表示されている HTML コンテナを、ビューと言います。

ビューは、モデルへアクセスが可能で、ビューにモデルデータを表示するためにはいくつかの方法があります。

指定したモデルのプロパティに、要素の innerHTML プロパティを結合する ng-bind ディレクティブを使用することができます:

<p ng-bind="firstname"></p>
Try it Yourself »

また、モデルからコンテンツを表示するには、二重の波括弧 {{ }} を使用することができます:

<p>First name: {{firstname}}</p>
Try it Yourself »

または、モデルをビューにバインドするため、HTML コントロールに ng-model にディレクティブを使用することができます。


ng-model ディレクティブ

モデルからのデータを HTML コントロール (input、select、textarea) のビューにバインドするため、 ng-model ディレクティブを使用します。

<input ng-model="firstname">
Try it Yourself »

ng-model directive provides a two-way binding between the model and the view.


双方向バインディング

AngularJS のデータバインディングは、モデルとビューの間を同期させます。

モデルのデータが変わると、ビューはその変化を反映し、ビューのデータが変わると、 モデルも同様に更新されます。 This happens immediately and automatically, which makes sure that the model and the view is updated at all times.

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

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});
</script>
Try it Yourself »

AngularJS コントローラ

AngularJS のアプリケーションは、コントローラによって制御されています。コントローラについては、 AngularJS コントローラ章をご覧ください。

モデルとビューは即時に同期するため、コントローラはビューから完全に分離されて、モデルデータに単に集中することができます。 (Because of the immediate synchronization of the model and the view, the controller can be completely separated from the view, and simply concentrate on the model data.) AngularJS におけるデータバインディングのおかげで、ビューにはコントローラで行った変更が反映されます。

<div ng-app="myApp" ng-controller="myCtrl">
    <h1 ng-click="changeName()">{{firstname}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.changeName = function() {
        $scope.firstname = "Nelly";
    }
});
</script>
Try it Yourself »