2015-01-21 3 views
0

공유 서비스를 통해 통신하는 컨트롤러가 두 대 있는데, 그 중 하나가 변경 사항에 대한 서비스 값을 감시합니다. 그러나 두 번째 시간 후에 값이 변경된 후에 만 ​​작동합니다.이 원인이 무엇일 수 있습니까?

export interface ISharedService { 
    value: customObject; 
} 

class SharedService implements ISharedService { 
    value: customObject; 
} 

export class Controller1 { 

    private sharedService : ISharedService; 

    constructor(sharedService : ISharedService) { 
     this.sharedService = sharedService; 
    } 

    changeValue(value: customObject) { 
     this.sharedService.value = value; 
    } 

} 

export class Controller2 { 

    constructor($scope : ng.IScope, sharedService : ISharedService) { 
     $scope.$watch(() => sharedService.value, (prev, cur) => { 
      if(prev !== cur) { 
       alert("WEEEEEE!"); 
      } 
     }); 
    } 

} 

.changeValue() 함수를 호출하여 값을 변경하면 아무 것도 발생하지 않습니다. 함수가 호출 된 후 두 번째로 갑자기 작동하기 시작합니다.

답변

0

실제로 코드를 가져 와서 누락 된 부분을 추가하고 나에게 적합합니다. 코드 여기

<div ng-app="myModule"> 
    <div ng-controller="Controller1 as vm"> 
     <div>changeCounter={{vm.changeCounter}}</div> 
    </div> 
    <hr> 
    <div ng-controller="Controller2 as vm"> 
     <div>sharedService.value={{vm.sharedService.value}}</div>  
     <button ng-click="vm.onClick()">Click</button> 
    </div> 
</div> 

것 :

class SharedService { 
    value: string; 
} 

class Controller2 { 

    private sharedService; 
    constructor(private sharedService) { 
     this.sharedService = sharedService; 
    } 

    onClick():void { 
     this.sharedService.value = Math.random(); 
    } 
} 

class Controller1 { 
    changeCounter = 0; 
    constructor($scope, sharedService) { 
     $scope.$watch(() => sharedService.value, (prev, cur) => { 
      if(prev !== cur) { 
       this.changeCounter = this.changeCounter + 1; 
      } 
     }); 
    } 

} 

angular.module("myModule", []) 
.service("sharedService", SharedService) 
.controller("Controller1", Controller1) 
.controller("Controller2", Controller2); 
여기

는 HTML의
관련 문제