oatmealsnap oatmealsnap - 6 months ago 11
AngularJS Question

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>


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



  .controller('Ctrl', function($scope) {

    var action = function() {

    $scope.items = [{
      label: 'Item 1',
      action: action
    }, {
      label: 'Item 2',
      action: action
    }, {
      label: 'Item 3',
      action: action
    }, {
      label: 'Item 4',
      action: action


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


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