Saturday, December 29, 2012

AngularJS with input file directive

How to make +AngularJS work with input file.

Problem: input type file doesn't work with +AngularJS
<input type="file" data-ng-model="param.file" data-ng-change="change($event)"/>

This doesn't work with angular. Unfortunately. The change event is not triggered. Model is not initialized. SNAFU. But with shining +AngularJS  feature called directive it is very easy to fix it and make it work elegantly without much efforts. Let's see.
index.html

<div
   data-ng-app="angularjstutorial.blogspot.com/2012/12/angularjs-with-input-file-directive.html"
   data-ng-controller="MainController">
   <input type="file" data-file="param.file"/>
   <div>param.file: {{param.file}}</div>           
</div>

script.js

module.directive('file', function(){
    return {
        scope: {
            file: '='
        },
        link: function(scope, el, attrs){
            el.bind('change', function(event){
                var files = event.target.files;
                var file = files[0];
                scope.file = file ? file.name : undefined;
                scope.$apply();
            });
        }
    };
});