Search code examples
angularjsangular-directive

calling a controller function from a link in a directive


I'm writing an Angular 1.5.0-beta2 project.

I want to call a controller function from the link property of the returned object.

which means...

angular.module('myalcoholist').directive("ngFileSelect",function() {

    return {
        controller: 'AddCoctailController',
        controllerAs: 'addCocktail',
        link: function ($scope, el) {

            el.bind("change", function (e) {

                var file = (e.srcElement || e.target).files[0];
/*THIS DOES NOT WORK */      addCocktail.getFile(file);
            })

        }

    }
});

as you can see here i'm trying to run a controller function called getFile.

is it even possible ?


Solution

  • If you use a angular >= 1.3, use bindToController option

    angular.module('myalcoholist').directive("ngFileSelect",function() {
    
        return {
            controller: 'AddCoctailController',
            controllerAs: 'addCocktail',
            bindToController: true,
            link: function (scope, el) {
    
                el.bind("change", function (e) {
    
                    var file = (e.srcElement || e.target).files[0];
                    scope.addCocktail.getFile(file);
                });
    
            }
    
        }
    });
    

    codepen: http://codepen.io/gpincheiraa/pen/VeYxGN