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