我找不到能帮助我解决Angular中这个简单问题的东西。与位置路径进行比较时,所有答案都与导航栏相关。
我使用list和构建了一个动态表ngRepeat。当我单击一行时,我试图为该行分配一个css类(选中),以突出显示该行已被用户选中的事实,并.selected从先前突出显示的行中删除了该行。
ngRepeat
.selected
我缺少在选定的行和CSS类分配之间进行绑定的方法。
我在每个row(ul)上应用了代码,ng-click="setSelected()" 但我缺少function应用更改的逻辑。
row
ul
ng-click="setSelected()"
function
我的代码-Plunk
我的代码:
var webApp = angular.module('webApp', []); //controllers webApp.controller ('VotesCtrl', function ($scope, Votes) { $scope.votes = Votes; $scope.statuses = ["Approved","Pending","Trash","Spam"]; $scope.setSelected = function() { console.log("show"); } }); //services webApp.factory('Votes', [function() { //temporary repository till integration with DB this will be translated into restful get query var votes = [ { id: '1', created: 1381583344653, updated: '222212', ratingID: '3', rate: 5, ip: '198.168.0.0', status: 'Pending', }, { id: '111', created: 1381583344653, updated: '222212', ratingID: '4', rate: 5, ip: '198.168.0.1', status: 'Spam' }, { id: '2', created: 1382387322693, updated: '222212', ratingID: '3', rate: 1, ip: '198.168.0.2', status: 'Approved' }, { id: '4', created: 1382387322693, updated: '222212', ratingID: '3', rate: 1, ip: '198.168.0.3', status: 'Spam' } ]; return votes; }]);
我的HTML:
<body ng-controller='VotesCtrl'> <div> <ul> <li class="created"> <a>CREATED</a> </li> <li class="ip"> <b>IP ADDRESS</b> </li> <li class="status"> <b>STATUS</b> </li> </ul> <ul ng-repeat="vote in votes" ng-click="setSelected()"> <li class="created"> {{vote.created|date}} </li> <li class="ip"> {{vote.ip}} </li> <li class="status"> {{vote.status}} </li> </ul> </div> </body>
我的CSS(仅选定的类):
.selected { background-color: red; }
每行都有一个ID。您要做的就是将该ID发送给函数setSelected(),将其存储($scope.idSelectedVote例如),然后检查每一行是否所选ID与当前ID相同。这里是一个解决方案(见文档的ngClass,如果需要的话):
setSelected()
$scope.idSelectedVote
ngClass
$scope.idSelectedVote = null; $scope.setSelected = function (idSelectedVote) { $scope.idSelectedVote = idSelectedVote; }; <ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}"> ... </ul>
[Plunker](http://plnkr.co/edit/SkaYSbtKFdx1I9N0xP5E?p=preview)