Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-ng-transclude

How to pass a function to transcluded scope from a controller (angular 1.3)?


I created a simple reusable collection container as a directive with an isolated scope an a transclude option is set to true.

app.directive('itemWrapper', function() {
  return {
    template: '...',
    replace: true,
    transclude: true,
    restrict: 'E',
    scope: {
      name: '=',
      isExpanded: '='
    }
  };

});

and a list view directive, where I'd like to pass a function from the controller that will handle clicks on list items

app.directive('listItem', function() {
      return {
        template: '...',
        replace: true,
        restrict: 'E',
        scope: {
          item: '=',
          action: '&'
        },
        link: function(scope, elm, attrs){
          scope.performAction = function(val){
            action({'data': val});
          };
        }
      };
});

my chunk of html looks in a following way:

<collection-wrapper name='item.name' is-expanded='item.visible'>
  <list-item item='item' action='log(data)'></list-item>
</collection-wrapper>

But when I click the link I get a Reference Error, saying that action is not defined. The question is, how to pass a function to this directive from a controller? As I understand, transcluded scope is a child of isolated scope and this is an obstacle I couldn't get over!

Here's a Plunkr.


Solution

  • action is a method on the scope. You need to say:

    scope.action({'data': val});
    

    http://plnkr.co/edit/gt6BgCpZ9qmOEJ8yS4UD?p=preview