Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 219
ufk Avatar asked Dec 24 '22 11:12

ufk


2 Answers

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

like image 114
Gonzalo Pincheira Arancibia Avatar answered Dec 28 '22 06:12

Gonzalo Pincheira Arancibia


Adding to Chris's answer above - link has several parameters (scope, element, attrs, controller). You can access the attached controllers functions doing the following:

link: function(scope, elem, attrs, ctrl){
    ctrl.func_to_call();
}
like image 31
Katana24 Avatar answered Dec 28 '22 06:12

Katana24