5

为了用时尚的假上传按钮替换丑陋的文件上传按钮,我使用 jquery 如下。

HTML

<input type='file' name='file' class='file_upload_btn' style='display:none'>
<button class='fake_upload_btn'>Upload Files</button>

jQuery

$('.fake_upload_btn').click(function() {
    $('.file_upload_btn').click();
})

现在,如果我想在 Angularjs 中做同样的事情,而不依赖于 Jquery 库,该怎么办。

4

1 回答 1

7

It is kind of workaround , and i have checked it only in chrome but try this:

<label for="uploader">
   <button class='fake_upload_btn'>Upload Files</button>
   <input id="uploader" type='file' name='file' class='file_upload_btn' style='display:none' />
</label>

JSFiddle: http://jsfiddle.net/84Xxb/

Click event on button is catched like a click on label and consequently input is also "clicked"!

UPDATE: But if you want a really "Angulary" solution , you need to use directives, like this:

app.directive('uploader', function () {
    return {
      template: "Upload Files <input type='file' name='file' class='file_upload_btn' style='display:none'>",
      link: function(scope, element, attrs) {   
        element.bind("click", function(){
          element.find("input")[0].click();
        });
      }
   }
});

Working example: http://plnkr.co/edit/DVALMH?p=preview

于 2013-09-01T07:18:02.303 回答