2014-09-19 54 views
1

我正在嘗試向單擊的元素添加一個類,並在用戶單擊其他元素時將其刪除。如何處理我的類中的單擊事件

我有類似

<li ng-repeat='test in tests' > 
    <a href='' ng-click='pickTest($index, $event)'>{{test.title}}</a> 
</li> 

JS

$scope.pickTest = function(index, event) { 
    $(event.target).addClass('blur'); 
    //this works when user clicks one of the <a> tags 
    //but I want to remove the class if user clicks another <a> tag 
    }; 

我該怎麼辦呢?

謝謝!

回答

4

您可以使用ng-class來確定是否需要根據某個條件附加類。此外,在ng-repeat中使用$index實際上並不可取,因爲在ng-repeat指令中應用了過濾器時會造成問題。您可以爲ng-class指令創建兩個功能,isActive()setActive()以設置活動項目。

angular.module('app', []) 
 

 
    .controller('Ctrl', function($scope) { 
 
    
 
    var activeTest = {}; 
 
    
 
    $scope.tests = [{ 
 
     title: 'Test 1' 
 
    }, { 
 
     title: 'Test 2' 
 
    }, { 
 
     title: 'Test 3' 
 
    }, { 
 
     title: 'Test 4' 
 
    }]; 
 
    
 
    $scope.setActive = function(test) { 
 
     activeTest = test; 
 
    }; 
 
    
 
    $scope.isActive = function(test) { 
 
     return angular.equals(activeTest, test); 
 
    }; 
 
    
 
    \t 
 
    });
.blur { 
 
    color: red; 
 
}
<div ng-app="app" ng-controller="Ctrl"> 
 
    <ul> 
 
    <li ng-repeat="test in tests"> 
 
     <a href="" ng-click="setActive(test)" ng-class="{blur: isActive(test)}">{{test.title}}</a> 
 
    </li>  
 
    </ul> 
 
</div> 
 

 

 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

2

使用納克級的,就像這樣:

<li ng-repeat='test in tests' > 
    <a ng-class={blur:blurActive} href='' ng-click='pickTest($index, $event);blurActive=true'>{{test.title}}</a> 
</li> 

請注意,您不需要設置blurActive到你的函數裏面真的,因爲ng-repeat會爲每個「重複項」新的範圍,所以你可以在同一個ng-click內設置它的激活狀態,在你調用你的函數之後,這樣你的函數邏輯就不會與設計混在一起。

0

只需選擇類別爲blur的所有其他元素,並在將類分配給當前點擊的element之前從中刪除類。

$scope.pickTest = function(index, event) { 
    $('.blur').removeClass('blur'); 
    $(event.target).addClass('blur'); 
}; 
+0

恐怕這不是 「角辦法」。爲什麼要重新發明輪子並手動操作DOM?這是什麼角度基本上讓你免於做。 – alecxe 2014-09-19 03:10:09

+0

那麼,我沒有經驗使用角度,混合標記與邏輯通常是我試圖避免的東西。 – 2014-09-19 03:21:27

1

在控制器做DOM操作被認爲是不好的做法,你可以實現使用ng-class這個角方式: -

<li ng-repeat="test in tests"> 
     <a href="#" ng-click="pickTest($index, $event)" 
      ng-class="{'blur': opt.selectedIdx == $index}">{{test.title}}</a> 
    </li> 

,並在你的控制器,只是做: -

$scope.opt = {}; //Set an initial value in your controller 

$scope.pickTest = function(index, $event) { 
    $event.preventDefault(); //If you need 
    $scope.opt.selectedIdx = index ; //Set the current index here, You could do this inline as well in the html, but probably better off having logic in your controller 
} 

Plnkr

相關問題