Angular.js How to change an elements css class on click and to remove all others

前端 未结 6 1621
南旧
南旧 2020-12-22 17:27

i\'m trying to make my two elements toggle, so if one element is clicked it will remove all references of my-class and apply it to its self. Any ideas?



        
6条回答
  •  渐次进展
    2020-12-22 18:03

    Create a scope property called selectedIndex, and an itemClicked function:

    function MyController ($scope) {
      $scope.collection = ["Item 1", "Item 2"];
    
      $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection
    
      $scope.itemClicked = function ($index) {
        $scope.selectedIndex = $index;
      };
    }
    

    Then my template would look something like this:

    {{ item }}

    Just for reference $index is a magic variable available within ng-repeat directives.

    You can use this same sample within a directive and template as well.

    Here is a working plnkr:

    http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

提交回复
热议问题