Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from input's onchange

Tags:

angularjs

I'm using controller as syntax.

And when my file input changed, i want to trigger a function.

how to do that?

below is my code with $scope syntax

<input class="upload" type="file" accept="image/*" ng-model="image"
                onchange="angular.element(this).scope().uploadImage(this)">
like image 631
Tran Thien Chien Avatar asked Jul 16 '26 03:07

Tran Thien Chien


1 Answers

As found here, you could use a custom directive to listen for changes in your input file.

view.html:

<input type="file" custom-on-change="uploadFile">

controller.js:

app.controller('myCtrl', function($scope){
    $scope.uploadFile = function(event){
        var files = event.target.files;
    };
});  

directive.js:

app.directive('customOnChange', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var onChangeHandler = scope.$eval(attrs.customOnChange);
      element.bind('change', onChangeHandler);
    }
  };
});

View JSFIDDLE

like image 197
Matheno Avatar answered Jul 17 '26 18:07

Matheno