2016-03-08 58 views
0

當我點擊任何html元素時,我希望它保持活動狀態,請參閱演示,在下面的演示中,如果我點擊了任何不活動的html,它將變爲活動狀態,或反之亦然。
DEMO如何在angularjs中單擊它時激活html元素?

<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> 

回答

0

你SH請使用ng-class在您的DOM上點擊設置一個類,因此還需要使用ng-click來調用功能來設置活動菜單。不需要在錨標籤中使用ng-model

可以試試

在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> 

在控制器:

$scope.selectedType= '' ;// initially empty 

$scope.makeActive = function(getName) { 
    $scope.selectedType = getName; 
} 

和CSS:選擇添加另一個類

.tag:hover, .selected { 
     background-color: red; 
     border-color: red; 
} 
0

的基本思想是爲具有範圍變量,將節省被單擊的按鈕(通過ng-click屬性)和有條件地分配一個css類(通過ng-class屬性)匹配鏈接。

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:

app.controller('myCtrl', function($scope) { 
    $scope.type = null; 
}); 

的CSS(爲active類):

.tag:hover, .active { 
    background-color: red; 
    border-color: red; 
} 

Forked plknr

相關問題