【问题标题】:how i use the $rootScope.$emit and $root.Scope.On?我如何使用 $rootScope.$emit 和 $root.Scope.On?
【发布时间】:2020-04-08 23:08:57
【问题描述】:

我的第一个控制器中有$rootScope.$emit,第二个控制器中有$rootScope.$on,以便在执行$emit 时进行监听。

调试的时候发现监听器不存在,只存在于另一个控制器中。

我做错了什么?

app.controller("Controlador", function ($scope, $window, baseServicio, $rootScope) {

    $rootScope.$on("Example", function(event) {
        console.log("hola");
    });    
});

app.controller("otherControlador", function ($scope, $window, myservicio, $timeout, $rootScope) {
    $rootScope.$emit("Example");    
});

【问题讨论】:

    标签: angularjs angularjs-directive angular-ui-router angularjs-scope


    【解决方案1】:

    将监听器放在 $scope 上:

    app.controller("Controlador", function ($scope, $window, baseServicio, $rootScope) {    
        ̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶.̶$̶o̶n̶(̶"̶E̶x̶a̶m̶p̶l̶e̶"̶,̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶(̶e̶v̶e̶n̶t̶)̶ ̶{̶
        $scope.$on("Example", function(event) {
            console.log("hola");
        });    
    });
    

    还有来自 $rootScope 的 $broadcast:

    app.controller("otherControlador", function ($scope, $window, myservicio, $timeout, $rootScope) {
        ̶$̶r̶o̶o̶t̶S̶c̶o̶p̶e̶.̶$̶e̶m̶i̶t̶(̶"̶E̶x̶a̶m̶p̶l̶e̶"̶)̶;̶
        $rootScope.$broadcast("Example");    
    });
    

    有关详细信息,请参阅

    【讨论】:

      【解决方案2】:

      您的代码没有任何问题,请确保首先调用“Controlador”以注册 $rootScope.$on 事件。 之后,当调用“otherControlador”时,它将调用 $emit,然后 $on 将监听 $rootScope.$emit("Example")。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多