范围.$ on在指令内创建时不起作用

Kan*_*agu 9 events directive broadcast emit angularjs

我已经为我的应用程序创建了一个指令,在下面的问题中提到了 如何使用AngularJS或Javascript提供下载文件?指令代码如下所示

    appModule.directive('fileDownload', function ($compile) {
        var fd = {
            restrict: 'A',
            link: function (scope, iElement, iAttrs) {

                scope.$on("downloadFile", function (e, url) {
                    var iFrame = iElement.find("iframe");
                    if (!(iFrame && iFrame.length > 0)) {
                        iFrame = $("<iframe style='position:fixed;display:none;top:-1px;left:-1px;'/>");
                        iElement.append(iFrame);
                    }
                    iFrame.attr("src", url);
                });
            }
        };
        return fd;
    });
Run Code Online (Sandbox Code Playgroud)

这里使用范围.$ on,当我通过$ scope.$ emit或$ scope.$ broadcast调用此事件时,它不起作用.我的控制器代码如下所示

    function reportsController($scope, $http) {
        var self = this;

        $scope.$broadcast("downloadFile", 'http://google.com');
        $scope.$emit("downloadFile", 'http://google.com');
    }
Run Code Online (Sandbox Code Playgroud)

我的html文件如下

    <div ng-controller="reportsController" id="repctrl">
        <a file-download></a>
    </div>
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

@Edit:在编译阶段添加了subscribe($ on),以避免在控制器中使用$ timeout.在这里你可以看一下这个例子

Aus*_*eco 7

我认为你的控制器正在你的指令之前被初始化..所以$on开始监听之后$emit,$broadcast已经发生了.

看到这个plunker

打开控制台,您可以看到console.logs何时发生:

controller init happened script.js:16
link happened script.js:7
$scope.test() happened script.js:21
scope.$on happened script.js:9
scope.$on happened 
Run Code Online (Sandbox Code Playgroud)

如果ng-view在创建指令后使用或初始化控制器或执行emit/broadcast,它应该可以工作.