[AngularJS rootScope。$ emit from Directive

问题描述 投票:0回答:1

我有一条指令供用户喜欢(或“收藏”)我的应用程序中的帖子。在我的整个控制器中,我使用$ rootScope。$ emit('函数名称',some-id)在用户喜欢新帖子时更新用户数据,因为这反映在我的整个应用程序中。但我似乎无法在指令中使用$ rootScope。$ emit。我收到一个错误

$ rootScope。$ emit不是函数

可能尚未调用与此命令相对应的$ rootScope。$ on事件,因此该功能尚不存在?关于这个还能做什么?有更好的方法来安排这个吗?

var module = angular.module('directives.module');

module.directive('postFave', function (contentService, $rootScope) {
return {
    restrict: 'E',
    templateUrl: 'directives/post-fave.html',
    scope: {
        contentId: '@',
        slug: '@'
    },
    link: function ($scope, $rootScope, element) {

        $scope.contentFavToggle = function (ev) {
            contentId = $scope.contentId;
            contentService.contentFavToggle(contentId, ev).then(function (response) {
                $rootScope.$emit('dataUpdated', $scope.slug);
                if (response) {
                    $scope.favourite[contentId] = response;
                } else {
                    $scope.favourite[contentId] = null;
                }
            });
        };

        console.log("track fave directive called");
    }
};
});

来自控制器:

var dataUpdatedListener = $rootScope.$on('dataUpdated', function (event, slug) {
    dataService.clearData(slug);
    dataControllerInit();
});

如何从指令中访问此rootscope函数?谢谢。

FYI-指令中已使用“链接”,因为它与HTML元素实例相关,该实例将在页面上使用多次]]

我有一条指令供用户喜欢(或“收藏”)我的应用程序中的帖子。在我的整个控制器中,我使用$ rootScope。$ emit('函数名称',some-id)在用户喜欢新帖子时更新用户数据,...

javascript angularjs angularjs-directive eventemitter angularjs-rootscope
1个回答
1
投票

[link具有以下签名,无需在$rootScope函数中添加link注入:

© www.soinside.com 2019 - 2024. All rights reserved.