Passing Parameters from a Directive to a Function – AngularJS

Hey everyone,

This is just a quick post to help out anyone who runs into the same problems with directives that I did today. I was able to call the controllers function from the directive, however none of the parameters were being passed.

The issue ended up being that the parameters need to be named. For instance:

 <ng-planner lessons="plannerLessons" lesson-clicked="editLesson(lesson)" add-lesson="newLesson()" business="true"></ng-planner>
app.directive('ngPlanner', function () {
    return {
        restrict: 'EA',
        templateUrl: '/Businesses/PlannerDirective',
        scope: {
            lessons: "=",
            business: "=",
            lessonClicked: "&",
            addLesson: "&"
        replace: true,
        link: function (scope, elem, attr) {
            var selectedIndex = null;
            scope.test = function (tester) {
                selectedIndex = tester;
                console.log("Directive: " + selectedIndex);
                scope.lessonClicked({ lesson: selectedIndex });
/* Used for handling business details, planner, etc */
app.controller("BusinessDetailsController", function ($scope) {
    //Fired when the new lesson button is clicked in the planner directive
    $scope.newLesson = function (date) {
        console.log("New Lesson Clicked: " + date);
    //Fired when a lesson is clicked on
    $scope.editLesson = function (lesson) {
        console.log("Lesson Clicked: " + lesson);

Note particularly the scope.lessonClicked line. Instead of passing parameters normally, they should be named (scope.lessonClicked({lesson: selectedIndex}).

The naming should match that used in the HTML where your directive is added:
<ng-planner lessons=”plannerLessons” lesson-clicked=”editLesson(lesson)” add-lesson=”newLesson()” business=”true”></ng-planner>

A huge thanks to Jay B for posting the solution on the AngularJS groups page:!topic/angular/3CHdR_THaNw

He’s also added the following JSFiddle:

And although pretty well hidden, it is actually mentioned in the documentation:

11 thoughts on “Passing Parameters from a Directive to a Function – AngularJS

  1. logan

    Thanks for the post! I was wondering why my function arguments (in the controller) were still undefined: it’s because I wasn’t correctly passing the object from the directive’s controller. Thanks for the tip!


Leave a Reply