AngularJS 1.3 Pictures

by otupman

HTML

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.5/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.5/angular-messages.js"></script>
<form novalidate="novalidate" name="testForm" ng:controller="MyFormCtrl">
    
    <input 
        type="file" 
        capture="camera" accept="image/*"  
        dts-picture-capture="gotPicture(pictureFile)"
        dts-max-size='1mb'
    />
    
    Picture: {{form.picture}}
    
</form>

JavaScript

angular
    .module('mcDemo', [])
    .controller('MyFormCtrl', function($scope) {
        $scope.form = {};
        $scope.gotPicture = function(pictureFile) {
            console.log('Got picture file', pictureFile);
        }
    })
.directive('dtsPictureCapture', function($parse) {
   return {
        restrict: 'A',
        controller: function($scope) {
            this.listeners = [];
            this.pictureChanged = function(pictureData) {
                console.log('pictureChanged - yo!');
                angular.forEach(listeners, function(listener) {
                    listeners.call(pictureData);
                });
            };
            this.listenForChanges = function(newListener) {
                this.listeners.push(newListener);
            };
        },
        link: function(scope, element, attrs, pictureCtrl) {
            
            var expressionHandler = $parse(attrs.dtsPictureCapture);
            
            var gotPicture = function(event) {
                var noPicture = !(event.target.files.length == 1 && event.target.files[0].type.indexOf("image/") == 0);
                 
                if(noPicture) { return; }

                var pictureFile = event.target.files[0];
                expressionHandler(scope, {pictureFile: pictureFile});    

                pictureCtrl.pictureChanged();
            };
                pictureCtrl.pictureChanged();            
            element.on('change', gotPicture);
        }
    };
})
.directive('dtsMaxSize', function() {
    return {
        require: 'dtsPictureCapture',
        restrict: 'A',
        link: function(scope, element, attrs, pictureCtrl) {
            var onPictureChanged = function(pictureData) {
                console.log('dtsMaxSize - change!');
            };
            pictureCtrl.listenForChanges(onPictureChanged);
        }
    };
})
;