문제

서비스에서 이벤트를 방출 / 브로드 캐스트하려는 간단한 예제를 코딩했으며,이 이벤트가 컨트롤러가 듣고 UI를 변경하고 싶지만 코드를 작동시키고 코드를 디버깅 할 수 없습니다.청취자에서 멈추는 것 같지만 함수를 실행하지 않습니다.

http://plnkr.co/edit/eglcq7zellfkp86dyzoe?p=preview <./ P>

서비스 :

angular.module('ServiceModule', []).
service('servicetest', ['$rootScope', function($rootScope){
    this.test = function(){
      $rootScope.$emit('testevent');
    };
}]);
.

컨트롤러

angular.module('ControllerModule', ['ServiceModule']).
    controller('ControllerTest', ['$scope','$rootScope','servicetest', function($scope, $rootScope, servicetest){
      $scope.name = 'World';
      servicetest.test();
      $rootScope.$on('testevent', function(){
        $scope.name = 'Joe';
      });
    }]);
.

지수

<!DOCTYPE html>
<html ng-app="ControllerModule">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js" data-semver="1.2.16"></script>
    <script src="controller.js"></script>
    <script src="service.js"></script>
  </head>

  <body ng-controller="ControllerTest">
    <p>Hello {{name}}!</p>
  </body>

</html>
.

솔루션 :

IVARNI 또는 Walter 브랜드가보고 된 이벤트가 아직 듣지 않는 이벤트가없는 이벤트가없는 이벤트를 트리거하지 않는 경우 이벤트를 트리거하지 않는 서비스 기능을 호출해야합니다. 우리는 다음과 같이 컨트롤러를 변경해야합니다.

서비스

angular.module('ControllerModule', ['ServiceModule']).
        controller('ControllerTest', ['$scope','$rootScope','servicetest', function($scope, $rootScope, servicetest){
          $scope.name = 'World';
          $rootScope.$on('testevent', function(){
            $scope.name = 'Joe';
          });
          servicetest.test();
        }]);
.

도움이 되었습니까?

해결책

리스너를 첨부하기 전에 이벤트를 트리거하고 있습니다.

시도 :

  $rootScope.$on('testevent', function(){
    $scope.name = 'Joe';
  });
  servicetest.test();
.

다른 팁

다음과 같이 컨트롤러의 청취자 아래에 ServiceTest.test ()를 배치하십시오.

  $rootScope.$on('testevent', function(){
    $scope.name = 'Joe';
  });
  servicetest.test();
.

테스트 ()를 호출 한 직후에 청취자를 첨부하고 이벤트를 놓치지 만

중간 크기의 앱에서 가장 잘 작동하는 솔루션은 $ EMIT 함수 주위에 래퍼를 만들고 몇 밀리 초의 $ EMIT를 지연시키는 것입니다. 현재 $ 범위를 전달하거나 $ ROOTSCOPE의 새로운 자식 범위를 만들 수있게 해주는 래퍼에 좀 더 맛있는 래퍼를 소개하거나 전파 할 때 여전히 빨리 일어날 수 있습니다.최대 $ Rootscope) 및 데이터 채널로 사용, 범위 후 이벤트 파괴 등을 사용하십시오 ...

여기에 전체 소스 코드가 있습니다 : http://jsfiddle.net/gabrielcatalin/2urr7 여기에 발췌문이 있습니다.

/**
 * Waits a given amount of time before calling emitting
 * This works well when the event registration happens before emitting.
 *
 * @param name
 * @param fn
 * @param wait
 */
this.delayEmit = function (name, fn, wait) {
    // Because of the $scope's lifecycle the $emit(publish) happens after the $on(subscription)
    //  therefore that needs to be taken care of with a delay
    $timeout(function () {
        self.emit(name, fn);
    }, wait || 100);
}
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top