1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
  <meta charset="UTF-8">
</head>
<body>
    <div id="controller1" data-ng-controller="controller1">
        컨트롤러1번영역
        X = {{x}}
        Y = {{y}}        
        <button data-ng-click="plusNumber()">데이터증가</button>
    </div>
    <div id="controller2" data-ng-controller="controller2">
        컨트롤러2번영역
        X = {{x}}
        Y = {{y}}    
        <button data-ng-click="plusNumber()">데이터증가</button>
    </div>
 
    <script type="text/javascript" src="lib/jquery/2.2.3/jquery.min.js"></script>
    <script type="text/javascript" src="lib/AngularJS/1.3.15/angular.min.js"></script>
    <script type="text/javascript">
 
        var myApp = angular.module("myApp", []);
 
        myApp.service('myService', function ($rootScope) {
            var x = 5;
            return {
                getX     : function () {
                    return x;
                },
                increment: function () {
                    x++;
                    $rootScope.$broadcast('XChanged', x); // $broadcast x 값을 감시하며 변경되었을때 알려준다. (이벤트등록)
                    // $broadcast는 자식 $scope에게 이벤트를 전파하고 $emit는 반대로 부모 $scope에게 이벤트를 전파한다.
                }
            };
        })
 
        myApp.controller("controller1", function ($scope, myService) { // myService 의존성주입
            $scope.x = 0;
            $scope.plusNumber = function () {
                myService.increment();
            }
            $scope.$on('XChanged', function (event, x) {
                console.log(event)
                $scope.x = x;
            });
        });
 
        myApp.controller("controller2", function ($scope, myService) {
            $scope.x = 0;
            $scope.plusNumber = function () {
                myService.increment();
            }
            $scope.$on('XChanged', function (event, x) {
                console.log(event)
                $scope.x = x;
            });
        });
 
    </script>
  
</body>
</html>


반응형
Posted by 힘없는염소