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');

      }
  };
});

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

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 -
Some interesting details about calling a callback function from directives tech.europace.de/passing-functions-to-angularjs-directives
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).

3 Comments

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 Unfortunately the official documentation is very lightweight on this (as is usual for angular). I added a short sentence to explain the syntax.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.