【发布时间】:2012-07-11 18:28:47
【问题描述】:
我正在尝试将 jQuery 插件 (Plupload) 与 AngularJS 一起使用。我创建了一个指令,它将成为我的文件上传“小部件”。指令长这样(链接函数中的代码是the example on the Plupload site的一个非常简化的版本):
.directive('myFileUpload', function () {
return {
restrict: 'E',
replace: true,
link: function(scope, element, attrs) {
scope.uploaderProperties = {
runtimes : 'html5,flash,html4',
url : 'media/upload',
max_file_size : '10mb',
container: 'fileUploadContainer',
drop_element: 'fileUploadDropArea'
};
scope.uploader = new plupload.Uploader(scope.uploaderProperties);
scope.uploader.init();
scope.uploader.bind('FilesAdded', function(up, files) {
scope.$apply();
});
},
templateUrl: 'upload.html'
};
});
我的 upload.html 文件如下所示:
<div id="{{uploaderProperties.container}}">
<div id="{{uploaderProperties.drop_element}}" style="border: 1px black dashed;">Drop files here<br><br><br></div>
Files to upload:<br>
<div ng-repeat="currFile in uploader.files">{{currFile.name}} ({{currFile.size}}) </div>
<br><br>
<!-- for debugging -->
{{uploader.files}}
<br><br>
</div>
当我在页面上包含带有<my-file-upload> 元素的指令时,所有数据绑定都会正确发生。问题是,当scope.uploader.init(); 运行时,id 还没有被插入到 DOM 中,所以 Plupload 抱怨和中断,因为它无法选择这些元素。如果我只是在模板中硬编码fileUploadContainer 和fileUploadDropArea id,它就可以正常工作。但是,我真的很想在一个地方定义这些 id。
那么,在链接模板后,有什么方法可以在上传器上运行init()?我考虑过使用$timeout 来延迟它的运行时间,但这对我来说似乎是一个相当大的黑客攻击。有没有更正确的方法来做到这一点?
更新
我像这样将init() 包裹在$timeout 中
$timeout(function() {
scope.uploader.init();
}, 2000);
只是为了确保它会按照我的想法运行,而且确实如此,通过这种延迟,插件可以正确设置并正常工作。但是,我不想依赖$timeout 的时间。如果在链接模板后我可以通过某种方式调用scope.uploader.init();,那么一切都应该正常。有人知道这样做的好方法吗?
【问题讨论】:
标签: javascript plupload angularjs