Shlomi Schwartz
Shlomi Schwartz

Reputation: 8913

AngularJS - How to bind to an ngRepeat element inside a directive

In my directive I have a template with ng-repeat,

 ...return {
       template:'<div id="wrapper"><ul><li ng-repeat="item in items">{{item.name}}</li></ul></div>',
       compile:function (tElement, tAttrs) {

        return function (scope, iElement, iAttrs) {
              //bind item mouse event to a closure function
        }
    }
    }...

I would like to bind each element of the repeater with a function inside my directive, what would be the best way?

Upvotes: 2

Views: 1976

Answers (1)

Valentyn Shybanov
Valentyn Shybanov

Reputation: 19391

You need to screate isolated scope and pass items to directive by adding scope: { items: '='} to directive definition object, then add handler to each item:

<span ng-click='clicked(item)'>{{item.name}}<span>

And in link function:

scope.clicked = function(item) { .. Do thmthng with item...};

And use it as <directive items='items' ...>

Upvotes: 3

Related Questions