Angularjs:$scope.emit不起作用

前端之家收集整理的这篇文章主要介绍了Angularjs:$scope.emit不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 angularjs的新手,我正在创建一个Web应用程序来赚取经验和实践.我的问题是$scope.$emit似乎没有工作,我正在寻找方法来联系控制器之间的功能,到目前为止,我已经在互联网上发现$scope.emit和$scope.on似乎适合对于这种任务,如果有另一种方式,我想知道,无论如何代码是这样编写的:

loginController.js

  1. (function(angular)
  2. {
  3. var app = angular.module('Organizer');
  4.  
  5. // inject $scope to the controller in order to try $scope.$emit
  6. app.controller('login',function($http,$scope)
  7. {
  8. // i define the scope like this so i can access inside other functions
  9. var scope = this;
  10. scope.processing = false;
  11. scope.message = null;
  12.  
  13. scope.submit = function()
  14. {
  15. scope.processing = true;
  16.  
  17. // store data for post
  18. var post = {
  19. username: scope.username,password: scope.password
  20. };
  21.  
  22. // send post data
  23. $http.post('api/default/login',post).
  24. success(function(data,status)
  25. {
  26. // hide processing Feedback and show the result
  27. scope.processing = false;
  28. scope.message = data.message;
  29. }).
  30. error(function(data,status)
  31. {
  32. scope.processing = false;
  33. });
  34. };
  35.  
  36. // Function i use to emit
  37. this.closeDialog = function()
  38. {
  39. $scope.$emit('closeDialog');
  40. };
  41. });
  42. })(angular);

siteController.js

  1. (function(angular)
  2. {
  3. var app = angular.module('Organizer');
  4.  
  5. app.controller('site',function($mdDialog,$scope)
  6. {
  7. this.menu = ['test1','test2'];
  8.  
  9. this.dialog = function()
  10. {
  11. $mdDialog.show({
  12. templateUrl: 'site/login',});
  13. };
  14.  
  15. // this does not seem to be working
  16. $scope.$on('closeDialog',function(event)
  17. {
  18. console.log('close dialog');
  19. });
  20. });
  21. })(angular);

注意:我正在使用角度材料,你可以看到我正在显示一个登录对话框,登录有它的控制器(我希望它使用相同的站点控制器,但我不知道如何),这个对话框有一个在loginControler中调用函数closeDialog()并且应该关闭对话框的按钮,但是现在出于测试原因我只是记录它是否正在调用该事件

$emit函数仅将事件传播给作用域父类.

$broadcast函数将事件传播给作用域子级.

那么你需要什么取决于控制器如何使用它……

如果您希望事件到达所有应用程序,则必须使用$rootScope:

  1. $rootScope.$broadcast('myEvent');

Here you have the doc of the scope,include $emit and $broadcast

猜你在找的Angularjs相关文章