2

I'm trying to learn Angular event listening. After a user clicks a button, the controller queries the database and returns a value in the button's handler. I'm having trouble passing this value to the $scope so that other functions can access the data.

First question: is this what event listeners are for? Is there another way to do what I want?

Next question: why doesn't this code work:

app.controller('EmitterCtrl', function($scope) {
  console.log("Emitter controller.");

  $scope.buttonClick = function() {
    console.log("Button clicked!"); // this works
    $scope.$emit('myEvent', 'Clicked!'); // child $scope
  };

  $scope.$on('myEvent'), function(event, data) { // parent $scope
    console.log("I heard it!"); // doesn't work
    console.log(event);
    console.log(word);
  };

});

<div ng-controller="EmitterCtrl">
  <button type="button" ng-click="buttonClick()">
    Click me!
  </button>
</div>

The user clicks the button, the event handler fires in the controller. The handler creates a child $scope so $emit sends the event to the parent $scope. Then the event isn't emitted, or the listener doesn't catch it.

Thomas David Kehoe
  • 10,040
  • 14
  • 61
  • 100
  • maybe this helps you [Linking one controller to another to call service on ng-click](https://stackoverflow.com/questions/34668416/linking-one-controller-to-another-to-call-service-on-ng-click/34702780#34702780) – Maher Jun 10 '17 at 01:52
  • I did some testing and my example has only one $scope, so $emit and $on are on the same $scope. In the project that I'm working on, the handlers ($scope functions) appear to create their own child scopes, but now I see that this is wrong. There must be something else wrong with my project. – Thomas David Kehoe Jun 10 '17 at 05:07

1 Answers1

5

$emit dispatches an event upwards ... $broadcast dispatches an event downwards

Detailed explanation

$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.

$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.

$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).

$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.

Ghazanfar Khan
  • 3,648
  • 8
  • 44
  • 89