【发布时间】:2013-12-17 07:15:55
【问题描述】:
我为我的应用程序创建了一个指令,该指令在以下问题中提到 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 调用此事件时,它不起作用。我的控制器代码如下所示
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),以避免在控制器中使用$timeout。 Here你可以看例子
【问题讨论】:
标签: angularjs events broadcast directive emit