Pierpaolo Croce Pierpaolo Croce - 2 months ago 32
AngularJS Question

read file directive with controller as

I m trying to buid a directive for upload and render a word file. I would like to use mammoth.js inside the directive. I wrote the following code:

(function() {
'use strict';
angular
.module('app.core')
.directive('uploadFile', uploadFile);

function uploadFile($parse) {
var directive = {

restrict: "A",
scope: false,
link: linkFunction,
controllerAs: "vm",


};

function linkFunction(scope, element, attrs) {
var fn = $parse(attrs.uploadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
console.log(reader);
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {
$fileContent: onLoadEvent.target.result
});
});
};

reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});

};

return directive;
}


})();


and in the controller:

vm.showContent = function($fileContent){
vm.content = $fileContent;
}


to start I want to render a simple txt file but the code doesn't works. I can not bind the .result in the controllor I think because the notation controller as but I can not fix it. Any suggestions?

Nix Nix
Answer

A slightly better pattern that relies on events. You could pull this same pattern off with a scope variable that is two way. Idea is you use an event to tell the controller data has changed.

function uploadFile($rootScope, $parse) {
    var directive = {
        restrict: "A",
        scope: {},
        link: linkFunction,

    };

    function linkFunction(scope, element, attrs) {
        var fn = $parse(attrs.uploadFile);
        element.on('change', function(onChangeEvent) {
            var reader = new FileReader();
            console.log(reader);
            reader.onload = function(onLoadEvent) {
              $rootScope.$broadcast('fileupdate', onLoadEvent.target.result);
            };
            reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
        });
    }
  return directive;
}

Inside of your controller you would listen for the fileupdate event.

//inside your controller:
$scope.$on('fileupdate', showContent);
function showContent(event, $fileContent){
   vm.content = $fileContent;
}