01/10/2018, 15:38

Bài 7: AngularJS – Data Binding

Data binding trong AngularJS có nhiệm vụ đồng bộ giữa model và view. Data Model AngularJS thường xuyên có một data model. Data model là một bộ sư tập các biến cho ứng dụng. Ex: var app = angular.module(‘myApp’, []); app.controller(‘myCtrl’, ...

Data binding trong AngularJS có nhiệm vụ đồng bộ giữa model và view.

Data Model

AngularJS thường xuyên có một data model. Data model là một bộ sư tập các biến cho ứng dụng.

Ex:

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
    $scope.firstname = “Ku”;
    $scope.lastname = “Tin”;
});

HTML View

HTML là nơi ứng dụng AngularJS hiển thị, được gọi là View.

View truy cập tới model và có vài cách hiển thị dữ liệu model trong view.

Bạn có thể sử dụng ng-bind directive.

Example:

<p ng-bind=”firstname”></p>

Bạn cũng có thể sử dụng 2 dấu ngoặc móc {{ }} để hiển thị nội dung từ model.

Example:

<p>First name: {{firstname}}</p>

ng-model Directive

Sử dụng ng-model directive để kết dữ liệu từ model tới view trong HTML controls(input,select,textarea)

Example:

<input ng-model=”firstname”>

ng-model directive cung cấp 2 cách binding giữa model và view.

Two-way Binding

Khi dữ liệu trong model thay đổi, thì view sẽ thay đổi, và khi dữ liệu trong view thay đổi, thì model sẽ cập nhập. Chúng xãy ra tức thì và tự động, mà bảo đảm rằng model và view cùng cập nhật ở tất cả thời điểm.

Example:

<!DOCTYPE html>

<html>

<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js”></script>

<body>

<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 = “Ku”;

    $scope.lastname = “Tin”;

});

</script>

<p>Change the name inside the input field, and the model data will change automatically, and therefore also the header will change its value.</p>

</body>

</html>

AngularJS Controller

Ứng dụng trong AngularJS được điều khiển bởi controller. (chúng ta sẽ học sâu hơn ở bài controller)

Bởi vì đồng bộ tức thì của model và view, controller có thể hoàn toàn tách biệt từ view và chỉ cần tập trung vào model.

Example

<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.firstname = “Sam”;

    $scope.changeName = function() {

        $scope.firstname = “Leo”;

    }

});

</script>

0