Reputation: 1190
I have an array of letters and I want to log whatever letter is clicked.
HTML:
<div class="col-md-2 col-sm-10 col-lg-1 letters"
ng-repeat="choice in images[num].letters track by $index">
<ul>
<li ng-click="displayLetter()"class="wordList">
{{choice}}
</li>
</ul>
</div>
JS:
$scope.displayLetter = function() {
console.log($scope.choice);
};
letters is stored inside an array of chars assigned to an object. The object is in an array of objects.
$scope.images =
[
{ pics: ["img/carrion.png", "img/telefrag.png", "img/thunder-skull.png", "img/skull-ring.png"], word: 'skull', length: 5,
letters: ['u', randLet(), randLet(), randLet(), 's', randLet(), 'k', 'l', randLet(), randLet(), randLet(), 'l' ]}
I keep getting undefined. How do I solve this?
I even tried adding an ng-model
<li ng-model="choice" ng-click="displayLetter()" class="wordList">
{{choice}}
</li>
Upvotes: 0
Views: 480
Reputation: 29
I do not know if I quite understand your question.
But you could do the following:
file.js
var app = angular.module('test', []);
app.controller('maincontroller', function($scope) {
$scope.displayLetter = function(clicked) {
console.log(clicked);
};
$scope.images = [{
"pics": [
"http://www.aviacaobr.com.br/wp/img.png",
"http://www.psf.gov.pk/images/icons/gallery.png",
"http://handicrafts.nic.in/dc_hc_photo_gallery.png"
],
"word": 'skull',
"length": 5,
"letters": [
'u',
randLet(),
randLet(),
randLet(),
's',
randLet(),
'k',
'l',
randLet(),
randLet(),
randLet(),
'l'
]
}];
function randLet(){
return 'a';
}
});
file.html
<li><body ng-controller="maincontroller">
<div class="col-md-2 col-sm-10 col-lg-1 letters"
ng-repeat="choice in images[0].letters ">
<ul>
<li ng-click="displayLetter(choice)" class="wordList">
{{choice}}
</li>
</ul>
</div>
The function displayLetter receive a parameter, that is the clicked item. And in ng-repeat, when ng-click call displayLetter pass the clicked item.
See in Plunker: Click Here
Upvotes: 0
Reputation: 23
The $scope
is for the controller itself not for every single item in ng-repeat
. Try it like this
<div class="col-md-2 col-sm-10 col-lg-1 letters">
<ul>
<li ng-repeat="choice in images[num].letters track by $index" ng-click="displayLetter(choice)" class="wordList">
{{choice}}
</li>
</ul>
</div>
$scope.displayLetter = function(choice) {
console.log(choice);
};
And as Lex mentioned below if you want each choice to be an li
then the ng-repeat
should on li
. If you 4
elements in array and have the ng-repeat
in the div
you would get 4
div
instead of 4
li
.
Upvotes: 2