Thursday, April 4, 2013

Form Fileuploader in purely AngularJS (NO jQuery included)

(You might like this AngularJS Tutorial: ngtutorial.com/tutorial.html)

html
    <form fileuploader onupload="onUpload" method="post" action="/statictest/test.json" enctype="multipart/form-data">
        <input type="file"></input>
        <input type="submit"></input>
    </form>

control,
 $scope.onUpload =function(o) {
        console.log('onUpload =', o);
    }


directive, note that adding listeners should be done during link as AngularJS docs have suggested.

(function(){
   
var oWidgetBasics = angular.module('widget.fileuploader',[]);
oWidgetBasics.directive('fileuploader', function(){
    return {
        restrict:'A',
        scope:false,
        compile: function compile(tElement, tAttrs, transclude) {
              return {
                    post: createFileuploader
              }
        }
    }
});

var cnt = 0;
var idprefix = '__tinood.com_fileuploader_id__';
var createFileuploader = function(scope, iElement, iAttrs, controller) {
    if ('FORM'!=iElement[0].nodeName) { return; }
    ++cnt;
    iElement[idprefix] = idprefix+'_'+cnt;
    var elIFrame = angular.element('<iframe id="'+iElement[idprefix]+'"></iframe>')
    iElement.append(elIFrame);
    iElement.attr('target', iElement[idprefix]);

    var onupload = iAttrs['onupload'];

    elIFrame.bind('load', function(){
        var framewin = elIFrame.prop('contentWindow');
        var elFrameDocBody = angular.element(framewin.document.body).contents();
        var o;
        try {
            o = JSON.parse(''+elFrameDocBody.html());
        } catch(e) {
            o = {};
        }
        if (!!onupload && 'function'==typeof(scope[onupload])) {
            scope[onupload](o);
        }
    });

};


})();