2014-03-04 58 views
1

確定這裏是名單:ng級的條件簡單列表?

<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

你想讓你的類按邏輯設置嗎?如果不是,則不需要使用ng-class來設置類,只需使用常規的HTML類屬性即可。

如果你不想手工添加ID(或通過NG重複),你可以做這樣的:

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'); 
    }; 

}); 

fiddle here

如果最終創造了<li>通過ng-repeat,你將能夠通過一個索引屬性,你可以使用它設置ID爲How to set repeated element id in AngularJS?

1

您可以使用一個範圍變量來跟蹤哪個項目被點擊。然後在您的NG-類,你可以檢查,如果當前元素是被點擊的一個:

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

那麼,在這裏是我的演示:

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-重複裏,有在HTML標記一個 '$指數'。 You can find it here.