好的,这是清单:
<ul>
<li ng-click="menuclick()" ng-class="testclass">test</li>
<li ng-click="menuclick()" ng-class="testclass">test</li>
<li ng-click="menuclick()" ng-class="testclass">test</li>
<li ng-click="menuclick()" ng-class="testclass">test</li>
这是我的控制器:
.controller('editcontroller', function ($scope) {
$scope.activemenufirst = 'activemenu';
$scope.menuclick = function menuclick() {
event.preventDefault();
$scope.activemenufirst = ' ';
alert('test');
};
});
如何点击li链接上的活动类并将其从所有其他li中删除? jsfiddle
答案 0 :(得分:1)
您可以使用范围变量来跟踪单击的项目。然后在你的ng-class中,你可以检查当前元素是否是被点击的元素:
HTML
<div ng-app="myApp">
<div ng-controller="editController">
<ul>
<li ng-click="menuclick(1)" ng-class="{active: clickedId === 1}">test</li>
<li ng-click="menuclick(2)" ng-class="{active: clickedId === 2}">test</li>
<li ng-click="menuclick(3)" ng-class="{active: clickedId === 3}">test</li>
<li ng-click="menuclick(4)" ng-class="{active: clickedId === 4}">test</li>
</ul>
</div>
</div>
的js
angular.module('myApp', [])
.controller('editController', function ($scope) {
$scope.menuclick = function menuclick(id) {
$scope.clickedId = id;
};
});
jsFiddle:http://jsfiddle.net/6B2ga/
答案 1 :(得分:1)
嗯,这是我的演示:
HTML:
<div ng-app="myApp">
<div ng-controller="editcontroller">
<ul>
<li ng-click="menuclick(1)" ng-class="{true:'activemenufirst',false:'testclass'}[active === 1]">test</li>
<li ng-click="menuclick(2)" ng-class="{true:'activemenufirst',false:'testclass'}[active === 2]">test</li>
<li ng-click="menuclick(3)" ng-class="{true:'activemenufirst',false:'testclass'}[active === 3]">test</li>
<li ng-click="menuclick(4)" ng-class="{true:'activemenufirst',false:'testclass'}[active === 4]">test</li>
</ul>
</div>
</div>
的javascript:
angular.module('myApp', [])
.controller('editcontroller', function ($scope) {
$scope.activemenufirst = 'red';
$scope.menuclick = function menuclick(index) {
event.preventDefault();
$scope.activemenufirst = ' ';
$scope.active = index;
};
});
如果你用ng-repeat制作你的li,html标记中有一个'$ index'。 You can find it here.
答案 2 :(得分:0)
你想让你的课程按逻辑设置吗?如果不是,您不需要在ng-class中设置类,您应该只使用常规HTML类属性。
如果您不想手动添加ID(或通过ng-repeat),您可以这样做:
angular.module('myApp', [
])
.controller('editcontroller', function ($scope) {
$scope.menuItems = angular.element(document.querySelectorAll('.testclass'));
$scope.menuclick = function menuclick(e) {
angular.forEach($scope.menuItems, function(el){
angular.element(el).removeClass('active');
});
angular.element(event.target).addClass('active');
};
});
如果您最终通过ng-repeat创建<li>
,则可以传入一个索引属性,您可以使用该属性设置ID How to set repeated element id in AngularJS?。