Angularjs:$ scope.emit不起作用

Osc*_*yes 6 angularjs angular-material

我是新手,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);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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

Fac*_*ini 11

在$发射功能传播的事件只对父母范围.

在$播放功能传播一个事件范围孩子的.

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

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

$rootScope.$broadcast('myEvent');
Run Code Online (Sandbox Code Playgroud)

在这里你有范围的文档,包括$ emit和$ broadcast