Simon Eliasson Simon Eliasson - 2 months ago 6
Javascript Question

Function call by expression in angularJS ng event

I have a problem where I want to map buttons created with ng-repeat to certain functions in the controller. I am defining a string with the function name like this:

$scope.sections = [
{
title: 'Music',
desc: 'Some examples of electronic music I have produced using Fl Studio.',
color: '#76a86f',
icon: 'img/icon/music.png',
onClick: 'clickMusic()'
}];


The function is defined like:

$scope.clickMusic = function() {
hideAll();
document.getElementById("musicContent").classList.remove("hide");
document.getElementById("musicContent").classList.add("show");
};


And then try to map the function to a html button like this:

<div ng-repeat="section in sections">
<div class="sectionThumbnail"">
<button ng-click="section.onClick">
<img ng-src="{{ section.icon }}" id="sectionnail_{{$index}}" ng-mouseover="sectionhoverIn($index)" ng-mouseleave="sectionhoverOut($index)">
</button>
<div class="sectionthumbnailInfo">
<p class="sectiontitle">{{ section.title }}</p>
{{ section.desc }}
</div>
</div>
</div>


However, when clicking the button, nothing happens. I know that the clickMusic() function works as intended once executed, since I use the same function for another button on the webpage. When directly referring to the clickMusic() function in the ng-click, like ng-click="clickMusic()", it also works. I get no error in the console either.

Is there any way to refer to functions from an array in this way, or do I have to create an additional function, which takes an index argument from the repeat and then map the index to the desired functions?

Thanks!

Answer

Change onClick: 'clickMusic()' to onClick: clickMusic (this way you store a reference to the function you want to call inside angular template) and then in ng-click simply call that funtion <button ng-click="section.onClick()">

Comments