[英]AngularJS: How to display an element on another div when clicked
I have an array of letters and I want to log whatever letter is clicked. 我有一个字母数组,我想记录单击的任何字母。
HTML: 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: 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 我什至尝试添加ng-model
<li ng-model="choice" ng-click="displayLetter()" class="wordList">
{{choice}}
</li>
The $scope
is for the controller itself not for every single item in ng-repeat
. $scope
适用于控制器本身,而不适用于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
. 就像Lex在下面提到的,如果您希望每个选择都成为
li
那么ng-repeat
应该在li
。 If you 4
elements in array and have the ng-repeat
in the div
you would get 4
div
instead of 4
li
. 如果您在数组中包含
4
元素,并且在div
具有ng-repeat
,则将获得4
div
而不是4
li
。
I do not know if I quite understand your question. 我不知道我是否完全理解你的问题。
But you could do the following: 但你可以做到以下几点:
file.js 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 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. 函数displayLetter接收一个参数,即单击的项目。 And in ng-repeat , when ng-click call displayLetter pass the clicked item.
并且在ng-repeat中 ,当ng单击呼叫displayLetter时,传递被单击的项目。
See in Plunker: Click Here 在Plunker中查看: 单击此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.