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!

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

2 Comments

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: stackoverflow.com/questions/24830679/…)
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 - and only actual listeners will be notified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.