2014-11-02 2 views
0

파일을로드 한 다음보기를 업데이트하기 위해 컨트롤러를 사용하는 서비스가 있습니다.
this.loadListAsync를 사용하면 컨트롤러가 아직 존재하지 않기 때문에 브로드 캐스트가 유효하지 않습니다. 다른 쪽에서는 $ emit 접근 방식을 사용하면 여기에 뭔가 빠져있는 느낌이 들지만 $ emit는 그렇지 않습니다. 목적AngularJs - 컨트롤러가 초기화를 완료했는지 확인하는 방법

var mod= angular.module('mod1', []); 
mod.service('modModel', ['$rootScope',function ($rootScope) { 

// here is how i know the controller finished initialization 
    $rootScope.$on('modController', function(ev, data){ 
     data.loadListAsync(); 
    }) 

    this.loadListAsync = function(){ 
     $.ajax({ 
      url:'mainapp/dashboardList.js', 
      type:'GET', 
      cache:false, 
      dataType: "script", 
      success :this.broadcast 
     }) 
    } 

    this.broadcast= function(){ 
     this.list = list; // list is loaded from the async call 
     $rootScope.$broadcast('modModel::list', list); 
    } 

// this.loadListAsync(); // this line is not working because the controller is not initialized yet 

}]); 

mod.controller('filtersController', ['$scope', 'sharedData', 'angularLoad','modModel', function ($scope, sharedData, angularLoad, modModel) { 

    $scope.$on(''modModel::list', function(event, list) { 

     $scope.list = list; 
     doThings(); 
    }); 

    $scope.$emit('modController',modModel) 
}) 

답변

0

여러 가지 선택 사항이 있는데, 하나는 $ emit 접근 방식입니다. 고유 한 이벤트 이름 (예 : 'loaded ::')을 전달하여 올바른 알림을 받고 있는지 확인할 수 있습니다. 통지를 받으면 핸들러를 등록하십시오. $ on은 unregister 함수를 $ on의 반환 값으로 제공합니다. 여기에 $ 값을 반환하십시오. angular doc for $on

하지만 단순히 콜백 함수를 전달하지 않는 것이 좋습니다. "this"컨텍스트를 포함하고 xyz.call(this_var, ... callback params)this.broadcast 안에있는 것처럼 호출 할 수 있습니까?

관련 문제