Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter to ng-click directive, within custom directive

I'm using ng-repeat in the template for a custom directive as follows:

<li ng-repeat="image in images">
    <img ng-src="{{image.url}}" ng-click="togglePhoto({{$index}})">
</li>

When rendered on the page the source looks like

<li ng-repeat="image in images" class="ng-scope">
    <img ng-src="http://example.com/example.jpg" ng-click="togglePhoto(1)" src="http://example.com/example.jpg">
</li>

I have the function togglePhoto defined in my directive. Without the {{index}} parameter being passed in it works and the function is called. With the index, it doesn't fire.

How do I get the index of the photo clicked into the togglePhoto function?

like image 858
markstewie Avatar asked Aug 28 '13 03:08

markstewie


Video Answer


2 Answers

Figured this out. Hope it helps anyone else stuck on it.

Firstly this

ng-click="togglePhoto({{$index}})"

Should be

ng-click="togglePhoto($index)"

Braces not needed!

Secondly I found that you can pass the event object into the click function eg

ng-click="togglePhoto($event)"

Then catch that event and find out what element trigged it in your click function

$scope.togglePhoto = function(e)
{
    console.log(e.currentTarget)
}
like image 83
markstewie Avatar answered Nov 02 '22 22:11

markstewie


I think that the issue is that you are using the double curly braces inside of the ng-click, and angular doesn't like that.

Try changing your repeater to this (note there are no curly braces around $index):

<li ng-repeat="image in images">
    <img ng-src="{{image.url}}" ng-click="togglePhoto($index)">
</li>

I also put together a working jsfiddle to show that this works.

http://jsfiddle.net/n02ms8s0/4/

like image 26
TwitchBronBron Avatar answered Nov 02 '22 22:11

TwitchBronBron