1. 서비스의 Data는 아래와 같이 2개의 컨트롤러에 의해 공유될 수 있다.
| 
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 | 
<!DOCTYPE html> 
<html > 
  <head> 
    <meta charset="utf-8"> 
  </head> 
  <body ng-app='helloApp'> 
    <div ng-controller='InputController'  
    ng-init="inputNum =0" class="well well-lg"> 
    <span class="label label-default">Input</span> 
    <input type='text' ng-model='inputNum' ng-change='calcNum()'> 
    <p> {{getResult()}}</p>     
    </div> 
    <div ng-controller='OutputController' class="well well-lg"> 
    <span class="label label-info">Output</span> 
    <p> {{getCurrent()}}</p>     
    </div> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> 
    <script> 
    var hello  = angular.module('helloApp',[]);  
    hello.factory("HelloFactory",function(){ 
      return { 
        sum: 0, 
        add:function(num){ 
          this.sum += num; 
        }, 
        getSum:function(){ 
          return this.sum; 
        } 
      }; 
    }); 
    hello.controller('InputController', function($scope, HelloFactory){ 
      $scope.getResult = function(){ 
        return HelloFactory.getSum(); 
      }; 
      $scope.calcNum= function(){ 
        HelloFactory.add(Number($scope.inputNum)); 
      }; 
    }); 
    hello.controller('OutputController', function($scope, HelloFactory){ 
      $scope.getCurrent = function(){ 
        return HelloFactory.getSum(); 
      }; 
    }); 
    </script> 
  </body> 
</html> | cs | 
2. 서비스의 Data를 공유하지 않으려면, 서비스가 함수를 반환하게끔 하고,
사용하는 곳에서는 new로 생성하면 된다.
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 | 
    hello.factory("HelloFactory",function(){ 
      return function(startValue){ 
        this.sum =  startValue; 
        this.add = function(num){ 
          this.sum += num; 
        }; 
        this.getSum = function(){ 
          return this.sum; 
        }; 
      }; 
    }); 
    hello.controller('InputController', function($scope, HelloFactory){ 
      var helloService = new HelloFactory(10); 
      $scope.getResult = function(){ 
        return helloService.getSum(); 
      };      
      $scope.calcNum= function(){ 
        helloService.add(Number($scope.inputNum)); 
      };       
    }); | cs | 
 
댓글 없음:
댓글 쓰기