Search code examples
angularjsangular-directive

How do I pass a function to an angular directive inside ng-repeat (arg is undefined)?


parent directive:

<autosuggest
    click-match="addTag(tag)">
</autosuggest>

The addTag function is defined in the parent controller. It gets called, but the argument is undefined.

Here is the <autosuggest> implementation:

scope: {
    clickMatch: '&'
}

And inside the view:

<li ng-repeat="match in matches">
    <span ng-click="clickMatch(match)">{{match.name}}</span>
</li>

The clickMatch function is calling the parent's addTag(tag) function except the argument tag is undefined.


Solution

  • Functions passes into directives via & appear on the isolated scope in a modified form. They take an object of key value pairs of

    variableNameInExternalTemplate: expressionInIsolatedScope
    

    In your case, the key is tag and the value is match, so your ng-click attribute should look like

    <span ng-click="clickMatch({tag: match})"></span>
    

    If you also want to pass $event from the click, you can do the same with with the $event variable

    <span ng-click="clickMatch({tag: match, $event: $event})"></span>
    

    Making sure that you add $event to the arguments list in the template where the directive is used

    <autosuggest click-match="addTag(tag, $event)"></autosuggest>