Created
January 5, 2017 23:25
-
-
Save debuggerpk/c2b2885b231aa57cd3b24ed94cf1cdc5 to your computer and use it in GitHub Desktop.
angular directive example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
export default function fileReader($q) { | |
'ngInject'; | |
return { | |
restrict: 'E', | |
scope: { | |
label: '@', | |
accept: '@', | |
maxSize: '@', | |
ngModel: '=' | |
}, | |
templateUrl: 'directives/file-reader/file-reader.html', | |
// replace: true, | |
require: '^ngModel', | |
link: function(scope, elm, atr, ngModelCtrl) { | |
//console.log(scope, elm, atr, ngModelCtrl); | |
ngModelCtrl.$render = function() {}; | |
// scope.fileName = ''; | |
// var $file = ''; | |
var $file = elm[0].querySelector('.overlay'); | |
// console.log($file); | |
// watch for a new file in input | |
$file.onchange = function(e) { | |
var el = e.target; | |
// console.log(el.value); | |
if (!el.value) { | |
return; | |
} | |
// scope.apply(); | |
var name = el.files[0].name; | |
// return the file contents in base64 format | |
var read = function(f) { | |
var d = $q.defer(); | |
// var size = parseInt(scope.maxSize); | |
var r = new FileReader(); | |
// console.log(size); | |
// console.log(f.size); | |
if (parseInt(scope.maxSize) <= f.size) { | |
d.reject(); | |
} else { | |
r.onload = function(ev) { | |
d.resolve(ev.target.result); | |
}; | |
r.onerror = function(ev) { | |
d.reject(ev); | |
}; | |
r.readAsDataURL(f); | |
} | |
return d.promise; | |
}; | |
$q.all(Array.prototype.slice.call(el.files, 0).map(read)) | |
.then(function(vals) { | |
scope.fileName = name; | |
// ng-model contains the binary value, file the file name is the view value | |
ngModelCtrl.$setViewValue(vals.length ? vals[0] : null); | |
}, function() { | |
scope.fileName = 'Unable to load file, please try again'; | |
// scope.$apply(); | |
}); | |
}; | |
scope.launch = () => { | |
$file.click(); | |
}; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment