Angularjs: $ scope.emit not working

I am new to angularjs and I am angularjs web application to gain experience and practice. The problem is that $scope.$emit does not seem to work, I'm looking for ways to connect functions between controllers, and so far I have found on the Internet that $scope.emit and $scope.on seem to be suitable for this type of task if there is another way, I would like to know one way or another the code is written as follows:

loginController.js

 (function(angular) { var app = angular.module('Organizer'); // inject $scope to the controller in order to try $scope.$emit app.controller('login', function($http, $scope) { // i define the scope like this so i can access inside other functions var scope = this; scope.processing = false; scope.message = null; scope.submit = function() { scope.processing = true; // store data for post var post = { username: scope.username, password: scope.password }; // send post data $http.post('api/default/login', post). success(function(data, status) { // hide processing feedback and show the result scope.processing = false; scope.message = data.message; }). error(function(data, status) { scope.processing = false; }); }; // Function i use to emit this.closeDialog = function() { $scope.$emit('closeDialog'); }; }); })(angular); 

siteController.js

 (function(angular) { var app = angular.module('Organizer'); app.controller('site', function($mdDialog, $scope) { this.menu = ['test1', 'test2']; this.dialog = function() { $mdDialog.show({ templateUrl: 'site/login', }); }; // this does not seem to be working $scope.$on('closeDialog', function(event) { console.log('close dialog'); }); }); })(angular); 

Note: I am using angular material, and you can see that I am showing a dialog that is login, the login has its own controller (I wanted it to use the same site controller, but I do not know how to do this), and in this there is a button in the dialog that calls the closeDialog() function in loginControler and should close the dialog, but now, for testing reasons, I just register if it triggers an event

+6
source share
2 answers

The $ emit function propagates the event only to field fields.

The $ broadcast function propagates the event to child scope objects.

So what you need depends on how the controllers use it ...

If you want the event to reach the whole application, you should use $ rootScope :

 $rootScope.$broadcast('myEvent'); 

Here you have a scope document, including $ emit and $ broadcast

+9
source

You cannot generate or translate in a dialog controller because the dialog in angular has an isolated area. Because of this, when you emit or broadcast an event, it will not go anywhere. Passing $ emit and $ broadcast only works when you have a scope hierarchy. $ emit propagates the event up the hierarchy and $ broadcast distributes the event hierarchy.

+1
source

Source: https://habr.com/ru/post/989161/


All Articles