2

I'm using the bootstrap popup modal window, and trying to $emit and event but for some reason the main page is not detecting the event. It's a pretty simple setup, but I can't figure out why. From what I can tell when viewing Batarang it appears the popup is a child scope of the main app scope so I thought it would work but it doesn't. In this simple app when you press 'ok' in the popup window it should set a value in the parent scope. Here's a plunker:

http://plnkr.co/edit/F2W1LaWSsqinaFpiISAr?p=preview

//Here's code where $emit is called in the child (Factory):
var modalInstance = $modal.open({
                templateUrl: 'popupMyWindow.html',
                pScope: parentScope,
                controller: 
                    function($scope, $modalInstance){
                        $scope.ok = function () {
                            $scope.$emit('ModalSelect', 'hello world');
                            $modalInstance.close(null);
                        }
                    },

//Here's where $on is called in the main controller:
 $scope.$on('ModalSelect', function (event, selected) {
            console.log('ModalSelect called successfully');
            $scope.selectedValue = selected;
        });

Thanks!

Rob
  • 479
  • 8
  • 16

1 Answers1

5

I'm not sure it's a good idea to pass $scope to a Service. $scope is very contextual to where it is placed in the View, so can you really know whether you should $emit or $broadcast? Also, it's more difficult to unit-test when you pass $scope. Instead, pass a callback function.

That being said, you are calling $emit on a $modal directive's scope, which may be an isolated scope (I don't know how that directive is defined) so it never reaches the parent.

So you can either do:

parentScope.$emit('ModalSelect', 'hello world');

Or, you can use $rootScope:

$scope.$root.$broadcast('ModalSelect', 'hello world');
New Dev
  • 48,427
  • 12
  • 87
  • 129
  • However this is bad practice. For one, performance: root will $emit to all child scopes in your app whether they are listening or not. Secondly you create a dependency to the rootScope thus reducing reusability (See: http://stackoverflow.com/questions/24830679/why-we-use-rootscope-broadcast-in-angularjs) – SKuijers Mar 18 '15 at 10:08
  • To be precise, `$emit` bubbles up the hierarchical chain, and `$broadcast` - down. So, root will `$emit` only to `$rootScope.$on` listeners. But even with `$broadcast` - the performance problem was fixed - [see this answer](http://stackoverflow.com/a/19498009/968155) - and only actual listeners will be notified. – New Dev Mar 18 '15 at 14:07