Search code examples
angularjsangularjs-directiveangular-controller

Calling callback function in directive doesn't work


I want the directive to pass a value to the callback function (that was defined in the controller). The function is never called, though, and I have no clue why.

HTML:

<input type='file' fileread success="fileUploaded(data)" name="myFile" id="myFile" />

DIRECTIVE:

myApp.directive('fileread', function() {
    return {
        scope: {
            callBack: '&success',
        },
        link: function (scope, element) {
            scope.callBack({data: "test"});
        }
    };
});

CONTROLLER:

myApp.controller('MyCtrl', function($scope){
    $scope.fileUploaded = function(data){
        console.log(data);
    };
})

FIDDLE: http://jsfiddle.net/v6r9L6g3/4/


Solution

  • You are missing ng-app and ng-controller in your html your html must be

     <div ng-app="myApp" ng-controller="MyCtrl">
    <input type='file' fileread success="fileUploaded(data)" name="myFile" id="myFile" />
    </div>
    Above will work fine Alternatively you can use your directive as follow

      myApp.directive('fileread', function() {
        return {
         scope: {
        success: '&',
        },
    link: function (scope, element) {
    
        scope.success({data: "test"});
    }
    };
    });
    

    And

    here is working example http://jsfiddle.net/31rpuobL/