สิ่งที่ควรรู้
Scope Attribute (@) คือ อะไร ?
Scope Attribute (@) เป็นการ Binding ข้อมูลรูปแบบตัวอักษร (String) ให้ใช้งานใน Scope ของ Directive
(function () {
var app = angular.module("application", []);
app.controller("demoController", function ($scope) {...});
app.directive("scopeadd", function () {
return {
restrict: 'E',
scope: {
someAttr: '@'
},
template: '{{someAttr}}'
};
});
})();
การใช้ Scope Attribute (@) เป็นการลดความซับซ้อนของโค้ดที่เขียนซึ่งสามารถเขียนอีกอย่างได้ดังนี้
(function () {
var app = angular.module("application", []);
app.controller("demoController", function ($scope) {...});
app.directive("scopeadd", function () {
return {
restrict: 'E',
template: '{{someAttr}}',
link: function (scope, element, attrs) {
scope.someAttr = attrs.someAttr;
}
};
});
})();
วิธีการทั้งสองแบบได้ผลเหมือนกัน
ตัวอย่างการใช้งาน Scope Attribute (@)
ทำต่อจากบทที่แล้ว โดยทำการเพิ่ม attribute name ให้กับ <developer>
<body ng-controller="demoController as demo"> <developer name="john" task="doIt(message)"></developer> <developer name="jane" task="doIt(message)"></developer> <developer name="Jim" task="doIt(message)"></developer>
ทำการ Binding name ใน Directive developer ให้สามารถใช้ค่า String ดังกล่าว ใน Directive ได้
ใน Directive developer ทำเพิ่มชื่อลงใน template
app.directive("developer", function () {
return {
restrict: 'E',
scope: {
task: '&',
name: '@'
},
template: '<div><p>{{name}}</p><input type="text" ng-model="work" />
<button ng-click="task({message:work})">Go to Work</button></div>'
};
});
จะได้ผลลัพธ์ดังนี้
