In this article I will explain with an example, how to use ng-change directive with FileUpload element (Input Type File) in AngularJS.
There is no binding support for FileUpload element (Input Type File) in AngularJS and hence ng-change directive cannot be used.
This article will illustrate how to use JavaScript OnChange event handler to call a function inside AngularJS Controller.
Using ng-change with FileUpload (Input Type File) in AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML FileUpload element (Input Type File) which has been assigned a JavaScript OnChange event handler.
Since there is no binding support for FileUpload element (Input Type File) in AngularJS, the method inside the Controller is invoked using the JavaScript OnChange event handler.
Note: Above will work only when AngularJS is run in Debug mode.
Inside the SelectFile function, the name of the selected File is displayed using JavaScript Alert Message Box.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.SelectFile = function (e) {
$window.alert(e.target.files[0].name);
};
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<input type="file" onchange="angular.element(this).scope().SelectFile(event)" />
</div>
</body>
</html>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads