我为我的应用程序创建了一个指令,在以下问题中提到
How do you serve a file for download with AngularJS or 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;
});
这里使用了 scope.$on,当我通过 $scope.$emit 或 $scope.$broadcast 调用此事件时,它不起作用。我的 Controller 代码如下
function reportsController($scope, $http) {
var self = this;
$scope.$broadcast("downloadFile", 'http://google.com');
$scope.$emit("downloadFile", 'http://google.com');
}
我的html文件如下
<div ng-controller="reportsController" id="repctrl">
<a file-download></a>
</div>
我在这里做错了什么?
@Edit:在编译阶段添加订阅($on)以避免在 Controller 中使用 $timeout。 Here你可以看看这个例子
最佳答案
我认为你的 Controller 在你的指令之前被初始化..所以 $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
初始化 Controller 或者在指令创建后进行发射/广播,它应该可以工作。
关于angularjs - scope.$on 在指令中创建时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20628109/