2017-03-18 93 views
1

我正在使用angular-modal-service库。我的逻辑是:当模式打开时,它将SomeService$rootScope.$broadcastSomeService的功能运行到模态控制器,这样我可以将资源从服务发送到我的模态控制器。但是,它不会触发。请帮我弄清楚我错过了什么。谢谢。angularjs模式服务广播和发布

**服务:**

angular.module('ng-laravel').service('SomeService', function($rootScope, Restangular, CacheFactory, $http) { 
    this.testFunction = function() { 
     console.log("from service"); 
     $rootScope.$broadcast('event', {success:'success'}); 
    }; 
} 

**控制器:**

$scope.show = function(customer_id) { 

     ModalService.showModal({ 
      templateUrl: 'modal.html', 
      inputs: { 
       customer_id: customer_id 
      }, 
      scope: $scope, 
      controller: function($scope, close) { 
       $scope.customer_id = customer_id; 
       $scope.close = function(result) { 
        close(result, 500); // close, but give 500ms for bootstrap to animate 
       }; 
       $scope.$on('event', function(event, data){ 
        alert('yes'); 
        console.log('from modal controller'); 
       }); 
      } 
     }).then(function(modal) { 
     SomeService.testFunction(customer_id, tour_id); 
      modal.element.modal(); 
      modal.close.then(function(result) { 
       $scope.message = "You said " + result; 
      }); 
     }); 
    }; 

切换它的工作原理的功能后,但... 我怎么能到模态传递数据?像ui-bs-modal一样,他们已经解决了。

+0

是否缺少'返回此;'你的服务? –

+2

@PrashantGhimire没有必要从服务中返回'this' ..''service'会隐式返回'this'(context)的功能 –

+0

很高兴知道! @PankajParkar;) –

回答

1

您在模态控制器绑定事件之前正在广播事件。因此,在广播事件之前,请确保事件监听器已注册(意味着模块控制器已被加载)。所以请在showModal方法后拨打SomeService.testFunction();

$scope.show = function(customer_id) { 
    ModalService.showModal({ 
     templateUrl: 'modal.html', 
     inputs: { 
      customer_id: customer_id 
     }, 
     scope: $scope, 
     controller: function($scope, close) { 
      //code as is 
      //listeners will get register from here. 
     } 
    }) 
    .then(function(modal) { 
     SomeService.testFunction(); //broadcasting event 
    }).catch(function(error) { 
     // error contains a detailed error message. 
     console.log(error); 
    }); 
}; 
+1

你可能应该从**'show.modal'承诺链**,因为它必须异步获取templateURL。 – georgeawg

+0

@georgeawg嘿谢谢你的队友。欣赏你的捕获.. :)我错过了那件愚蠢的事情;) –

+0

这很好,它的工作原理。我花了几个小时。 :( –

1

你是广播事件,模态控制器被实例化或创建之前,作为服务功能ModalService.showModal之前调用。尝试改变顺序。这应该很好。

里面$scope.show试试这个顺序

$scope.show = function(){ 
ModalService.showModal({ 
     .... 
     // Listen for broadcast event 
}); 
SomeService.testFunction(); 
}