สิ่งที่ควรรู้
การใช้ $scope ใน controller
โดยปกติการใช้ $scope ใน Controller จะเป็นการระบุถึงการใช้งานภายใน controller โดยมีลักษณะดังนี้
1 2 3 | app.controller( 'someController' , function ($scope, $http) { $scope.someData = "..." ; }); |
โดยไม่จำเป็นที่จะต้องเรียงลำดับตัวแปรก็ได้
1 2 3 | app.controller( 'someController' , function ($http, $scope) { $scope.someData = "..." ; }); |
แต่มันเกิดปัญหาขึ้นที่ว่า เมื่อมีการบีบอัดไฟล์ js ทำให้ $scope ถูกแก้ไขชื่อเป็นตัวแปรอื่น ทำให้ AngularJS หา $scope ไม่เจอ AngularJS จึงใช้วิธีแก้ดังนี้
โดยไม่ได้สนใจว่าตัวแปรจะเป็นอะไร แต่จะเรียงลำดับให้ตามข้อความที่ระบุไว้ด้านหน้าฟังก์ชั่น
แนะนำให้ใช้ตัวแปรเดียวกัน เพื่อการ clean code
1 2 3 | app.controller( 'someController' , [ '$scope' , '$http' , function (x,y) { x.someData = "..." ; } ] ); |
การใช้ scope ใน Directive
ลักษณะ scope ใน Directive จะไม่เหมือนใน Controller ที่ระบุชื่อตัวแปรที่ต้องใช้ไว้แล้ว
โดยในฟังก์ชั่น link จะเรียกลำดับพารามิเตอร์ดังนี้
- scope
- element
- attribute
1 2 3 4 5 6 7 8 9 | app.directive( "someDirective" , function () { return { restrict: 'E' , template: '{{someAttr}}' , link: function (scope, element, attribute) { .... } }; }); |
ในฟังก์ชั่น link สามารถเปลี่ยนชื่อตัวแปรเป็นอะไรก็ได้ เนื่องจากไม่สนใจชื่อตัวแปร
แนะนำให้ใช้ชื่อตัวแปรเดิม เพื่อการ clean code
1 2 3 4 5 6 7 8 9 10 | app.directive( "someDirective" , function () { return { restrict: 'E' , template: '{{someAttr}}' , link: function (x, y, z) { // x is scope, y is element, z is attribute .... } }; }); |