Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

Is there a way to pass multiple functions to an AngularJS directive?


I am building a dropdown menu directive which allows you to optionally attach a function to each item in the list. I know how to pass one function per attribute into the directive, but I'm hoping that there is a way to pass multiple functions.

<dropdown items="['item1', 'item2']" actions="['action1()', 'action2()']"></dropdown>

or better yet:

<dropdown items="[{'item1':action1()}, {'item2':action2()}]"></dropdown>

which could be used to generate:

<dropdown items="['item1', 'item2']" actions="['action1()', 'action2()']">
    <a ng-click="action1()">item1</a>
    <a ng-click="action2()">item2</a>
</dropdown>

Solution

  • You can use the = object notation for your scope in accepting an array of objects with properties that you can assign to your directive.

    DEMO

    Controller

      .controller('Ctrl', function($scope) {
    
        var action = function() {
          window.alert(this.label);
        };
    
        $scope.items = [{
          label: 'Item 1',
          action: action
        }, {
          label: 'Item 2',
          action: action
        }, {
          label: 'Item 3',
          action: action
        }, {
          label: 'Item 4',
          action: action
        }];
      })
    

    Directive

      .directive('dropdown', function() {
        return {
          restrict: 'E',
          scope: {
            items: '='
          },
          template: 
            '<div ng-repeat="item in items track by $index" ng-click="item.action()">' + 
              '<a ng-bind="item.label"></a>' +
            '</div>'
        };
      });
    

    index.html

      <body ng-controller="Ctrl">
        <dropdown items="items"></dropdown>
      </body>