gpt4 book ai didi

javascript - AngularJS:如何在单击时将事件类设置为列表项?三元法

转载 作者:行者123 更新时间:2023-11-28 19:04:06 25 4
gpt4 key购买 nike

我是 AngularJS 的新手,Javascript 经验有限。我正在尝试设置 .active当单击 ul 列表项时,将其类化。我正在使用 ng-repeat 指令来列出项目。如何编写三元表达式以使我的示例正常工作? Full plnkr here .

查看:

<li ng-repeat="item in list" ng-click="$index = item.id">
<a href="#" ng-class="(item.id == $index) ? 'active' : ''">
<div style="float: left;"><img src="http://placehold.it/100x100"></div>
<h3 style="padding-left: 5em;">{{item.title}}</h3>
</a>
</li>

Controller :

app.controller('TestCtrl', function($scope) {
$scope.list = [
{
"id": 0,
"title": "Batman",
"plot": "some stupid plot of a movie."
},
{
"id": 1,
"title": "Superman",
"plot": "another plot here."
},
{
"id": 2,
"title": "Xmen",
"plot": "asdfadsf asdfasdfasd asdfasdfdsf."
},
{
"id": 3,
"title": "Avengers",
"plot": "asdfasdf asdfdddd a3234323 dsfdf."
}
]
});

如果有更简单的方法,请随时告诉我。不过,我喜欢三元设置。谢谢!

最佳答案

试试这个:

angular.module('testApp', [])

.controller('homeCtrl', ['$scope', function($scope) {

$scope.setSelected = function(index) {
$scope.selected = index;
console.log($scope.selected);
}

$scope.list = [
{
"id": 0,
"title": "Batman",
"plot": "some stupid plot of a movie."
},
{
"id": 1,
"title": "Superman",
"plot": "another plot here."
},
{
"id": 2,
"title": "Xmen",
"plot": "asdfadsf asdfasdfasd asdfasdfdsf."
},
{
"id": 3,
"title": "Avengers",
"plot": "asdfasdf asdfdddd a3234323 dsfdf."
}
];

}]);
.active {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.angularjs.org/1.4.3/angular.min.js"></script>
<title>Document</title>
</head>
<body ng-app="testApp">
<section ng-controller="homeCtrl">
<li ng-repeat="item in list" ng-click="setSelected($index)">
<a href="#" ng-class="{'active': item.id == selected}">
<div style="float: left;"><img src="http://placehold.it/100x100"></div>
<h3 style="padding-left: 5em;">{{item.title}}</h3>
</a>
</li>
</section>
</body>
</html>

关于javascript - AngularJS:如何在单击时将事件类设置为列表项?三元法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32027417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com