Reputation: 1295
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!
Upvotes: 0
Views: 62
Reputation: 1295
Thanks to mic4ael's suggestion. I managed to figure it out.
in the controller:
$scope.sections = [
{
title: 'Music',
desc: 'Some examples of electronic music I have produced using Fl Studio.',
color: '#76a86f',
icon: 'img/icon/music.png',
onClick: $scope.clickMusic
}];
The $scope is there due to my function being defined as:
$scope.clickMusic = function() {
hideAll();
document.getElementById("musicContent").classList.remove("hide");
document.getElementById("musicContent").classList.add("show");
};
And then, just as mic4ael suggested, in HTML:
<button ng-click="section.onClick()">
Upvotes: 0
Reputation: 8300
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()">
Upvotes: 2