如何清除角JS文件输入 [英] How to clear a file input from Angular JS

查看:103
本文介绍了如何清除角JS文件输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AngularJS,我在这里使用说明来处理INPUT TYPE =文件的方法。

In AngularJS, I'm using the approach described here to handle input type=file.

  • https://groups.google.com/forum/?fromgroups=#!topic/angular/-OpgmLjFR_U
  • http://jsfiddle.net/marcenuc/ADukg/89/

标记:

<div ng-controller="MyCtrl">
    <input type="file" onchange="angular.element(this).scope().setFile(this)">
    {{theFile.name}}
</div>

控制器:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
    $scope.setFile = function(element) {
        $scope.$apply(function($scope) {
            $scope.theFile = element.files[0];
        });
    };
});

正如前面提到的这是一个黑客位,但它主要适用于我的目的。然而,什么我需要的是一种方法来清除文件输入上传完成后 - 即:从控制器

As mentioned it's a bit of a hack, but it mostly works for my purposes. What I need however is a way to clear the file input after the upload has finished - ie: from the controller.

我可以完全破解它,并使用jQuery或有事找输入元素和清除它,但希望的东西多了几分优雅。

I could completely hack it and use jQuery or something to find the input element and clear it, but was hoping for something a little more elegant.

推荐答案

我肯定会用指令为这种任务的。

I would definitely use directive for this kind of task.

http://plnkr.co/edit/xLM9VX

app.directive('fileSelect', function() {
  var template = '<input type="file" name="files"/>';
  return function( scope, elem, attrs ) {
    var selector = $( template );
    elem.append(selector);
    selector.bind('change', function( event ) {
      scope.$apply(function() {
        scope[ attrs.fileSelect ] = event.originalEvent.target.files;
      });
    });
    scope.$watch(attrs.fileSelect, function(file) {
      selector.val(file);
    });
  };
});

请注意:这是使用jquery的元素创建

note: it is using jquery for element creation.

这篇关于如何清除角JS文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆