javascript - AngularJS - 在链接模板后调用 javascript 的任何方式?

标签 javascript plupload angularjs

我正在尝试将 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> 的指令时元素,所有数据绑定(bind)都正确发生。问题是,当scope.uploader.init();运行时,id 尚未插入到 DOM 中,因此 Plupload 提示并中断,因为它无法选择这些元素。如果我只是硬编码 fileUploadContainerfileUploadDropArea ids 在模板中,它工作得很好。但是,我真的很想只在一个地方定义这些 ID。

那么,有什么方法可以运行 init()在模板链接后在 uploader 上?我考虑过使用 $timeout延迟它运行的时间,但这对我来说似乎是一个很大的技巧。有没有更正确的方法来完成这个?

更新

我包装了 init()$timeout像这样

$timeout(function() {
    scope.uploader.init();
}, 2000);

只是为了确保它的行为符合我的想法,果然,有了这个延迟,插件就可以正确设置并运行了。但是,我不想依赖 $timeout 的时间安排。 .如果有什么方法我可以调用scope.uploader.init();链接模板后,一切正常。有人知道这样做的好方法吗?

最佳答案

您的问题实际上是相反的 - 链接功能发生在 模板被放入之后。因此在这种情况下,scope.uploaderProperties 没有在模板发生时设置。

看起来您的模板对于 templateUrl 选项来说太花哨了,真的。您可以尝试使用 jQuery 手动设置您的 ID,或者在编译函数中设置所有内容。

http://docs.angularjs.org/guide/directive

关于javascript - AngularJS - 在链接模板后调用 javascript 的任何方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11444494/

相关文章:

ios - Plupload with iOS 仅适用于新照片,不适用于相机胶卷

javascript - 相同条件下的多个 ng-if - 性能方面

javascript - 具有两个输出目录的 TypeScript 共享代码库

javascript - 如何在不使用窗口的情况下从 html 访问函数

javascript - Plupload - 上传完成后的功能?

angularjs - 将 IEnumerable 从 web api Controller 发送到 angular js

angularjs - 使用 navigateTo 后等待 AngularJS 初始化

javascript - 是否存在 `x.valueOf() === x` 可能返回 `false` 的情况?

javascript - "prompt not defined"从命令行使用 Node ?

javascript - 使用 node.js 处理 PLUpload 上传