สิ่งที่ควรรู้
ใน rootScope จะมีฟังก์ชั่นต่างๆ ที่ใช้ในการจัดการข้อมูลต่างๆ
เช่น $watch, $apply, $broadcast, $on, $emit, $destroy อยู่
$watch() คือ อะไร ?
$watch เป็นฟังก์ชั่นที่ใช้ในการติดตามการเปลี่ยนแปลงของข้อมูล โดยมีโครงสร้างดังนี้
$watch(function1, function2);
ฟังก์ชั่นแรกจะ return ค่า ซึ่งจะคืนค่าที่กำลังติดตามอยู่ จะถูกเรียกทุกครั้งเมื่อฟังก์ชั่น digest() ทำงาน (Angular จะทำการเรียก digest() ทุกครั้งอัตโนมัติ)
$watch(
// ฟังก์ชั่นนี้จะ return ค่าที่ทำการติดตามอยู่ โดยจะถูกเรียกทุกครั้งที่มีการเรียก digest()
function () {
return watchedData;
},// ฟังก์ชั่นนี้จะถูกเรียกใช้ เมื่อมีการเปลี่ยนแปลงค่า
function ( newValue, oldValue ) {
}
);
เมื่อเกิดการเปลี่ยนแปลงของข้อมูล data ไม่ว่าจะมาจาก Controller ,Directive หรือจากหน้าจอ
$watch จะทำการเรียกใช้งานฟังก์ชั่น doSomething()
ตัวอย่างการใช้งาน $watch
สร้าง Controller เก็บตัวอักษร และจำนวนตัวอักษร
angular.module('application', [])
.controller('demoController', function($scope) {
$scope.text = "";
$scope.textLength = 0;
$scope.$watch(function () { return $scope.text; }, function (newData, oldData) {
console.log("change " + newData.length + " : " + oldData.length);
if (newData.length !== oldData.length) {
$scope.textLength = newData.length;
}
});
});
ทำการเรียกใช้ demoController ใน html
<div ng-controller="demoController as demo">
<input name="text" ng-model="text" />
<p>Text is : {{text}}</p>
<p>Length is : {{textLength}}</p>
</div>
จะได้ผลลัพธ์ดังนี้
Text is : "{{text}}"
Length is : {{textLength}}
