Directive ทั้งหมดที่เรารู้จักไปนั้นเป็นที่ AngularJS กำหนดขึ้น

แต่เราก็สามารถกำหนด Directive ของเราขึ้นมาเองได้เหมือนกัน เรียกว่า Custom Directive

ชนิดของ Custom Directive

Custom Directive มีทั้งหมด 2 แบบ คือ

  • Element Directive
  • Attribute Directive

มาสร้าง Custom Directive กัน

โดย Custom Directive มีโครงสร้างดังนี้

1
2
3
4
5
6
7
8
9
app.directive('someDirective', function(){
    return {
        restrict: 'E', // ชนิดของ Directive 'E'lement or 'A'ttribute
        templateUrl: 'someFile.html', // เป็นส่วนที่กำหนด template ภายในของ directive ตัวนั้น
        controller: function () {}, // ในกรณีที่จำเป็นต้องใช้การคิด Logic หรือมีฟังก์ชั่นการทำงาน
        link: function () {} //ส่วนที่ทำการ binding event ให้กับองค์ประกอบใน directive
         
    };
});

โดยการกำหนดชื่อของ directive ใน javascript จะใช้แบบ camelCase

1
app.directive('taskManager', function () {...});

และการใช้งาน directive ใน html จะใช้แบบ dash

1
2
3
4
<!-- Element Directive-->
<task-manager></task-manager>
<!-- Attribute Directive-->
<div task-manager=""></div>

หมายเหตุ: การกำหนด Custom Directive แบบ Element อาจจะมีปัญหาเกิดขึ้นในการใช้งานกับ IE (Internet Explorer)

ผมจะไม่กล่าวถึง Custom Directive มากนัก เนื่องจากเนื้อหาเชิงลึกค่อนข้างมาก