hussain hussain - 1 month ago 19
AngularJS Question

How to pass param from directive method to controller?

I want to send object from directive to controller

$scope
when method inoked but
file
printing undefined in controller , Any idea what is implemented wrong in below code ?
main.html

<input type="file" file-model="myFile" callback-fn="uploadFile()"style="display: none;"/>


directive.js

angular.module('App').directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
scope: { callbackFn: '&' },
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;

element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
console.log('test',element[0].files[0]);
var file = element[0].files[0];
scope.callbackFn(file);
});
});
}
};
}]);


controller.js

$scope.uploadFile = function(file){
file = $scope.myFile;
console.log('FILE',file);

};

Answer

To send that parameter you should do a couple of changes:

Specify it in your expression:

<input type="file" file-model="myFile" callback-fn="uploadFile(file)"style="display: none;"/>

Then in your directive when calling that callback you must also specify it:

element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
                console.log('test',element[0].files[0]);
                var file = element[0].files[0];
               scope.callbackFn({ file: file}); <--- here
            });
        });
    }
Comments