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

标签 javascript angularjs

我是 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/

相关文章:

java - 使用 Spring MVC + Angular JS 进行 Windows 身份验证

javascript - jQuery:如何隐藏 div 中除 2 个特定元素之外的所有内容

javascript - 类型错误 : e is undefined in d3. min.js

javascript - JQuery attr不设置最大值但设置html输入标签的最小值

javascript - vanilla js - 获取另一个元素内的元素 ID,这不是文档的一部分

javascript - 如何运行使用 yeoman 创建的 AngularJS 应用程序

javascript - Angular Dir-Pagination 并调用 Controller 功能

html - Angular : How to change the color of cell table if condition is true

javascript - 如何将 Redux 4.0 TypeScript 绑定(bind)与 redux-thunk 结合使用

javascript - 更改嵌套 alt 标签中的 img