Thursday 22 November 2012

เทคนิคการ Share Data ระหว่าง Controller ใน Angular.js

สำหรับเทคนิคต่อไปนี้ เป็นการใช้ข้อมูลร่วมกันระหว่าง Controller โดยใช้วิธีการ bind Service ลองดูตามตัวอย่างดังต่อไปนี้ครับ

<!doctype html>
<html ng-app="project">
<head>
    <title>Angular: Service example</title>
    <script src="http://code.angularjs.org/angular-1.0.1.js"></script>
    <script>
var projectModule = angular.module('project',[]);

projectModule.factory('theService', function() { 
    return {
        thing : {
            x : 100
        }
    };
});

function FirstCtrl($scope, theService) {
    $scope.thing = theService.thing;
    $scope.name = "First Controller";
}

function SecondCtrl($scope, theService) {  
    $scope.someThing = theService.thing;
    $scope.name = "Second Controller!";
}
    </script>
</head>
<body> 
    <div ng-controller="FirstCtrl">
        <h2>{{name}}</h2>
        <input ng-model="thing.x"/>        
    </div>

    <div ng-controller="SecondCtrl">
        <h2>{{name}}</h2>
        <input ng-model="someThing.x"/>            
    </div>
</body>
</html>

จากตัวอย่าง เมื่อเรามีการ update ข้อมูลใน Service จะส่งผลให้ Controller ที่ Bind เอาไว้กับข้อมูลใน Service มีการเปลี่ยนแปลงตามไปด้วย

1 comment:

  1. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog
    Angularjs Training In Hyderabad

    ReplyDelete