我有一个项目列表,当用户点击它们时会突出显示(使用selectedData类)。
<div>Remove highlight </div>
<ul>
<li ng-repeat="data in inputData">
<span title="{{data}}" ng-class="selected ? 'selectedData' : ''" ng-click="selected = !selected;">
{{data}}
</span>
</li>
</ul>
当我点击列表外的清除按钮时,我希望删除所有列表项的高亮显示(删除selectedData类),换句话说,重置selected
对于每个<li>
。由于ng-repeat创建了自己的范围,我该如何实现这一目标。
答案 0 :(得分:1)
试试这个:
<li id="list"... ng-repeat...>
<span ng-class="selected: selected[$index] ? 'selectedData' : ''" ng-click="selected[$index] = !selected[$index]">
</li>
function clear() {
for (i = 0; i < selected.length; i++) {
selected[i] = false;
}
}
答案 1 :(得分:0)
@Sidharth Panwar的回答大多是正确的
但我不确定selected:
中是否需要<span ng-class="selected: selected[$index] ? 'selectedData' : ''"
,我设法让它只与trenary运算符一起使用:
// Code goes here
angular.module("app",[])
.controller("controller", function($scope){
$scope.selected=[]; // <--- this is the most important part of the solution
$scope.clearSelector = function(){
for(var i = 0; i < $scope.selected.length; i++){
$scope.selected[i] = false;
}
};
});
&#13;
.highlight{
color:red;
}
&#13;
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@*" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
</head>
<body ng-controller="controller">
<ul ng-init="temp=[1,2,3]">
<li ng-repeat="i in temp" ng-click="selected[$index] = !selected[$index]" ng-class="selected[$index]?'highlight':''">
toggel between black and red
</li>
</ul>
<button ng-click="clearSelector()">clear</button>
</body>
</html>
&#13;
如果您担心ng-repeat
拥有自己的作用域,并且您无法从父作用域操作其值(其中&#34;清除&#34;按钮是),则创建父范围中的数组可以帮助您集中控制变量:
// both in child scope
selected=1; // create a new variable if no existing variable named
//"selected" in the current scope,
// this happens when javascript knows how to create stuff ie:primitives
selected[0]=1; // need to know the address of "selected", if we can't
// find it in the current scope, look it up in the parent scope
有关详细信息,请查看有关inheritance and scope
的链接