Scope Two way Binding (=) คือ อะไร ?

Scope Two way Binding (=) เป็นการ Binding ข้อมูลที่มีลักษณะเป็น Object ให้ใช้งานใน Scope ของ Directive

ลักษณะการใช้ของ = จะคล้ายๆกับ @ แต่ถ้าใช้ @ เราจะได้เฉพาะ String แต่ถ้าใช้ = เราจะได้ข้อมูลมาทั้ง Object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(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'
        };
    });
      
})();

ทำต่อจากบทที่แล้ว โดยใน Controller ให้กำหนดตัวแปรชนิด object john jane jimโดยมีคุณสมบัติเป็น name และ task ดังนี้

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 ออก

9
10
11
12
<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

1
2
3
4
5
6
7
8
9
10
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>'
    };
});

จะได้ผลลัพธ์ดังนี้

John

Jane

Jim