สิ่งที่ควรรู้
$destroy() คือ อะไร ?
$destroy เป็นฟังก์ชั่นที่ทำการลบ scope ที่เรียกใช้และ scope ที่เป็นลูกหลานออกจาก rootScope
และลบ event ต่างๆที่เรา binding ไว้ใน jQuery และ DOM Element
โดยมีโครงสร้างดังนี้
$destroy();
ตัวอย่างการใช้งาน $destroy
ในไฟล์ js ทำการสร้าง directive timer จะแสดง log ให้ดูว่า timer ถูกใช้งานแล้ว
angular.module('application', [])
.controller('demoController', function ($scope) {
$scope.choice = "true";
$scope.toggle = function () {
if ($scope.choice === "true") {
$scope.choice = "false";
} else {
$scope.choice = "true";
}
};
})
.directive('timer', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
var timer = $timeout(
//wait 2 sec and do this function
function () {
console.log("Timeout Executed", Date.now());
},
2000
);
timer.then(
//if timer is executed
function () {
console.log("Timer resolved!", Date.now());
},// else timer is not executed
function () {
console.log("Timer rejected!!", Date.now());
}
);
scope.$on("$destroy", function (event) {
// when ng-switch destroy element will cancel old timer
$timeout.cancel(timer);
});
}
};
});
ในไฟล์ html ทำการกำหนดดังนี้
หมายเหตุ: ng-switch จะแสดงผลเฉพาะ case ที่ถูกต้อง และ destroy element ที่ไม่ใช่ออกไป
ซึ่งการทำงานจะต่างกับ ng-show,ng-hide ที่ทำการซ่อน/แสดงเฉยๆ
<div ng-app="application" ng-controller="demoController as demo"> <button ng-click="toggle()">change choice</button> <div ng-switch="choice"> <p ng-switch-when="true" timer> Oh, Timer run </p> <p ng-switch-when="false" timer> Wow, Timer run agian </p> </div> </div>
จะได้ผลลัพธ์ดังนี้ (เปิด console เพื่อดู log)
choice is : {{choice}}
Oh, Timer run
Wow, Timer run agian
สังเกตได้ว่าเมื่อมี destroy element timer จะถูกยกเลิก และแสดงผลให้เห็นว่า timer ถูก rejected แล้วเริ่ม timer ตัวใหม่
