我是
angularjs的新手,我正在创建一个Web应用程序来赚取经验和实践.我的问题是$scope.$emit似乎没有工作,我正在寻找方法来联系控制器之间的功能,到目前为止,我已经在互联网上发现$scope.emit和$scope.on似乎适合对于这种任务,如果有另一种方式,我想知道,无论如何代码是这样编写的:
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);
注意:我正在使用角度材料,你可以看到我正在显示一个登录对话框,登录有它的控制器(我希望它使用相同的站点控制器,但我不知道如何),这个对话框有一个在loginControler中调用函数closeDialog()并且应该关闭对话框的按钮,但是现在出于测试原因我只是记录它是否正在调用该事件
$emit函数仅将事件传播给作用域父类.
$broadcast函数将事件传播给作用域子级.
那么你需要什么取决于控制器如何使用它……
如果您希望事件到达所有应用程序,则必须使用$rootScope:
- $rootScope.$broadcast('myEvent');
Here you have the doc of the scope,include $emit and $broadcast