Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - Fire button2's click event by clicking button1 (fake upload button)

Tags:

angularjs

To replace ugly file upload button with stylish fake upload button, I use jquery as below.

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();
})

Now what if I want do the same in Angularjs, without Jquery library dependency.

like image 581
user1995997 Avatar asked Sep 01 '13 07:09

user1995997


People also ask

How do you trigger a click event in Angularjs?

The syntax is the following: function clickOnUpload() { $timeout(function() { angular. element('#myselector'). triggerHandler('click'); }); }; // Using Angular Extend angular.

How do you trigger a click button?

and a trigger to execute the button1 click event handler. $("#button2"). bind("click", (function () { alert("Button 2 is clicked!"); $("#button1").

What is the difference between Ng click and Onclick?

Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.


1 Answers

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

like image 159
Ivan Chernykh Avatar answered Sep 20 '22 17:09

Ivan Chernykh