22

I would like to send a call back into a directive via a parameter on the tag, and then call that method when appropriate inside the directive. For example, when a button was clicked call a method on the parent controller.

I have a simple plunker of it not working

html file:

<body ng-controller="ParentController">
    <h1> Method Arguments </h1>
    <h3> open console to view output</h3>
    <hello-world onLoadCallback="myCallback(arg1)"></hello-world>
</body>

javascript file:

var app = angular.module("app",[]);

function ParentController($scope) {
  $scope.myCallback = function(var1){
    console.log("myCallback", var1);
  }
}
app.directive('helloWorld', function() {
  return {
      restrict: 'AE',
      template: '<h3>Hello World!!</h3>',
      scope:{
            onLoadCallback: '&'
        },
        link: function(scope, element, attrs, dateTimeController) {
            console.log('linked directive, not calling callback')
            scope.onLoadCallback('wtf');

      }
  };
});
user1338062
  • 11,939
  • 3
  • 73
  • 67
nakkor
  • 895
  • 1
  • 7
  • 11

2 Answers2

43

Tricky tricky angular, when declaring the argument in the HTML, it needs to use snake case, instead of camelcase to match.

Works:

<hello-world on-load-callback="myCallback(arg1)"></hello-world>

Doesn't Work:

<hello-world onLoadCallback="myCallback(arg1)"></hello-world>
nakkor
  • 895
  • 1
  • 7
  • 11
  • 1
    html is not aware of cases, so it doesn't know if it is onloadcallback or if it is onLoadCallback. also browser some time do some case/element modification, that's why angular and even JS, for example elem.dataSet, translate camel case to `-` – Hassan Faghihi Jan 20 '16 at 08:57
  • 1
    Some interesting details about calling a callback function from directives http://tech.europace.de/passing-functions-to-angularjs-directives/ – Ron Harlev Mar 29 '18 at 16:50
28

Also the callback needs to be:

scope.onLoadCallback({arg1: 'wtf'});

The named parameters are then bound to the corresponding parameters used in the callback attribute (not all need to be used).

user1338062
  • 11,939
  • 3
  • 73
  • 67
  • This answer has been flagged as low quality and is up for review. Might I request you to kindly improve the answer by describing why the code needs to be changed to the one that you have proposed - perhaps you can provide a link to the documentation AND a short description about why you need to explicitly mention the parameter – callmekatootie Mar 04 '15 at 09:22
  • 1
    @callmekatootie Unfortunately the official documentation is very lightweight on this (as is usual for angular). I added a short sentence to explain the syntax. – user1338062 Mar 04 '15 at 09:27
  • 1
    Can confirm that this the paramater syntax is correct if you are trying to pass more than one paramater to your callback. If you dont use this syntax, angular fails to map both parameters to the callback. – asulaiman Aug 26 '15 at 16:22