Image Preview and Form Data
Choose a file, it is previewed. On submit it is sent as text.
HTML
<form data-ng-app="app" data-ng-controller="UploadImageController">
<input data-ng-model="image.title" />
<br />
<canvas id="image-preview"></canvas>
<br />
<input type="file" data-input-file-preview="image-preview" data-map-to-model="image.file" />
<br />
<input type="submit" data-ng-click="send(image)" />
<pre>{{sentData}}</pre>
</form>
CSS
canvas {
max-height: 100px;
max-width: 100px;
}
JavaScript
(function (angular) {
angular.module('app', [])
.directive('inputFilePreview', [function () {
var canvas, mapToModel, elementScope;
/**
* To be fired when the image has been loaded
*/
var imageOnLoad = function () {
canvas.width = this.width;
canvas.height = this.height;
canvas.getContext("2d").drawImage(this, 0, 0);
};
/**
* To be fired when the FileReader has loaded
* @param loadEvent {{}}
*/
var readerOnLoad = function (loadEvent) {
var img = new Image();
img.onload = imageOnLoad;
img.src = loadEvent.target.result;
if (mapToModel) {
setModelValue(elementScope, mapToModel, img.src);
}
};
/**
* This allows us to set the value of a model in the scope of the element (or global scope if the
* model is an object)
* @param scope {{}}
* @param modelReference {string}
* @param value {*}
*/
var setModelValue = function (scope, modelReference, value) {
// If the model reference refers to the propery of an object (eg. "object.property")
if (~modelReference.indexOf('.')) {
var parts = modelReference.split('.', 2);
// Only set the value if that object already exists
if (scope.hasOwnProperty(parts[0])) {
scope[parts[0]][parts[1]] = value;
return;
}
}
scope[modelReference] = value;
};
/**
* The logic for our directive
* @param scope {{}}
* @param element {{}}
* @param attributes {{}}
*/
var link = function (scope, element, attributes) {
elementScope = scope;
canvas = document.getElementById(attributes.inputFilePreview);
if...