ufk
ufk

Reputation: 32104

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 ?

Upvotes: 4

Views: 9907

Answers (3)

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

Upvotes: 6

Chris Hermut
Chris Hermut

Reputation: 1758

Controller is to populate $scope and link is running after controller so you can just access whatever is on your scope in link function.

angular.module('app', [])
  .directive('tstDrv', function () {
      return {
          restrict: 'E',
          template: '<div>{{hello}}</div>',
          link: function (scope) {
              console.log(scope.hello);
              scope.hello = "hello again";
          },
          controller: function ($scope) {
              $scope.hello = 'tst';
          }
      }
  })

Also this SO question is related Angular: calling controller function inside a directive link function using &

If one wants to access a scope property that has been defined outside of current directive scope it all depends on scope property of 'Domain Definition Object'.

Ref. https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance

Upvotes: 2

Katana24
Katana24

Reputation: 8959

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();
}

Upvotes: 2

Related Questions