避免 $rootScope.$on — 它有内存泄漏的风险

Avoid $rootScope.$on — it risks memory leaks

Angularjs: 订阅指令中的服务事件不会更新

我正在尝试 $emit/$broadcast 服务中的事件并在指令中订阅它,但它没有被触发。

在这种情况下,我同时尝试了 $emit$broadcast,但尽管两者都出现在控制器中,但都未出现在指令中。

有人知道如何完成这个吗?

angular.module('my_app', [])

.service('my_service', ['$rootScope', function($rootScope) {
    this.do_something = () => {
        $rootScope.$emit('myEvent');
        $rootScope.$broadcast('myEvent');
    }
}])

.directive('myDirective', ['$rootScope', function($rootScope) {
    return {
        scope: {
            some_var: '@?'
        },
        link: function(scope, element, attrs, controller) {
            $rootScope.$on('myEvent', ()=>{
                console.log('event fired in directive');
            })
        }
    }
}])

.controller('my_controller', ['$rootScope', 'my_service', function($rootScope, my_service) {
    $rootScope.$on('myEvent', ()=>{
        console.log('event fired in controller');
    })

    my_service.do_something();

}])

和 html:

<my-directive ng-if="some_expression"></my-directive>

在这种情况下我只得到:

event fired in controller
event fired in controller

避免$rootScope.$on — 它有内存泄漏的风险

在其操作过程中,AngularJS 添加和删除 DOM 及其附加的指令和控制器。 $rootScope.$on 添加的侦听器函数不会在删除指令或控制器时自动删除。这可能会导致内存泄漏和意外行为。

为了避免内存泄漏, 将事件侦听器添加到控制器的 $scope,而不是 $rootScope:

.controller('my_controller', ['$scope', 'my_app_service', function($scope, my_app_service) {
    $scope.$on('myEvent', ()=>{
        console.log('event fired in controller');
    }
    my_app_service.do_something();    
}])

使用指令,在链接函数中添加事件侦听器:

.directive('myDirective', function() {
    return {
        link: postLink
    }
    function postLink(scope, elem, attrs) {    
        scope.$on('myEvent', ()=>{
            console.log('event fired in directive');
        });
    }
})

来自文档:

Scope Events Propagation

Scopes can propagate events in similar fashion to DOM events. The event can be broadcasted to the scope children or emitted to scope parents.

有关详细信息,请参阅


更新

I corrected my question as I do actually have the event listener in the linking function. But still not working.

确保指令的名称在 JavaScript 中的 camelCase:

.̶d̶i̶r̶e̶c̶t̶i̶v̶e̶(̶'̶m̶y̶_̶d̶i̶r̶e̶c̶t̶i̶v̶e̶'̶,̶ ̶[̶f̶u̶n̶c̶t̶i̶o̶n̶(̶)̶ ̶{̶
.directive('myDirective', [function() {
   // ...
}])

kebab-case中的HTML:

<my-directive>
</my-directive>