[英]How to active html element when clicked on it in angularjs?
When I click on any html element, I want to it to remain active, Please see the demo, In following demo, if I clicked on any inactive html, then it becomes active, or vise-versa. 当我单击任何html元素时,我希望它保持活动状态,请参见演示。在以下演示中,如果我单击了任何不活动的html,则它将变为活动状态,反之亦然。
DEMO 演示
<div class="wrapper col-md-12 col-sm-12">
<a title="week? category" ng-model="week" class="tag">week</a>
<a title="week? category" ng-model="month" class="tag">month</a>
<a title="week? category" ng-model="year" class="tag">year</a>
</div>
The basic idea is to have a scope variable that will save which button is clicked (via the ng-click
attribute) and to conditionally assign a css
class (via the ng-class
attribute) to the matching link. 基本思想是拥有一个范围变量,该变量将保存单击哪个按钮(通过ng-click
属性),并有条件地将css
类(通过ng-class
属性)分配给匹配的链接。
Html file: HTML文件:
<div ng-app="myApp" ng-controller="myCtrl as vm">
<div class="wrapper col-md-12 col-sm-12">
<!--
when you click the link, it will set $scope.type to the define type
('week' in the first case),
we then compare $scope.type with some hardcoded value to set the
class and change the css properties accordingly)
Of course, you could extract this to a $scope method
-->
<a title="week? category" ng-class="{active: vm.type=='week'}" ng-click="vm.type = 'week'" class="tag">week</a>
<a title="week? category" ng-class="{active: vm.type=='month'}" ng-click="vm.type = 'month'" class="tag">month</a>
<a title="week? category" ng-class="{active: vm.type=='year'}" ng-click="vm.type = 'year'" class="tag">year</a>
</div>
</div>
Javascript: Javascript:
app.controller('myCtrl', function($scope) {
$scope.type = null;
});
Css (for the active
class): CSS(对于active
类):
.tag:hover, .active {
background-color: red;
border-color: red;
}
See Forked plknr 参见分叉的plknr
you should use ng-class
to set a class in your DOM on click so also need to use ng-click
to call a function to set active menu. 您应该使用ng-class
在点击时在DOM中设置一个类,因此还需要使用ng-click
调用函数来设置活动菜单。 No need to use ng-model
in anchor tag. 无需在锚标记中使用ng-model
。
Can try it 可以尝试一下
In HTML: 在HTML中:
<div ng-app="myApp" ng-controller="myCtrl">
<div class="wrapper col-md-12 col-sm-12">
<a title="week? category" class="tag" ng-class="{selected:selectedType == 'week'}" ng-click="makeActive('week')">week</a>
<a title="week? category" class="tag" ng-class="{selected:selectedType == 'month'}" ng-click="makeActive('month')">month</a>
<a title="week? category" class="tag" ng-class="{selected:selectedType == 'year'}" ng-click="makeActive('year')">year</a>
</div>
</div>
in Controller: 在控制器中:
$scope.selectedType= '' ;// initially empty
$scope.makeActive = function(getName) {
$scope.selectedType = getName;
}
and in css: add another class selected 并在CSS中:添加另一个选定的类
.tag:hover, .selected {
background-color: red;
border-color: red;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.