angularjsmodal-dialogbroadcastangular-broadcast

angularjs modal service broadcast and on issue


I am using angular-modal-service library. My logic is : when the modal is open it runs a function from SomeService, and $rootScope.$broadcast from SomeService to modal controller that way I can send resource from service to my modal controller. However, it doesn't fire. Please help me to figure out what I have missed. Thank you.

**Service: **

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

**Controller: **

$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;
            });
        });
    };

After switching the function it works, but... how could i pass data in to modal? like ui-bs-modal, they have resolve.


Solution

  • You're being broadcasting event before events from modal controller are binding. So before broadcasting event make sure that event listeners are registered(meaning modal controller has been loaded). So call SomeService.testFunction(); after showModal method.

    $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);
        });
    };