我已经为我的应用程序创建了一个指令,在下面的问题中提到了 如何使用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 = $(""); iElement.append(iFrame); } iFrame.attr("src", url); }); } }; return fd; });
这里使用范围.$ on,当我通过$ scope.$ emit或$ scope.$ broadcast调用此事件时,它不起作用.我的控制器代码如下所示
function reportsController($scope, $http) { var self = this; $scope.$broadcast("downloadFile", 'http://google.com'); $scope.$emit("downloadFile", 'http://google.com'); }
我的html文件如下
我在这做错了什么?
@Edit:在编译阶段添加了subscribe($ on),以避免在控制器中使用$ timeout.在这里你可以看一下这个例子
我认为你的控制器正在你的指令之前被初始化..所以$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
如果ng-view
在创建指令后使用或初始化控制器或执行emit/broadcast,它应该可以工作.