What is the best way to conditionally apply a class?

后端 未结 22 2581
感动是毒
感动是毒 2020-11-22 09:12

Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex.

22条回答
  •  时光取名叫无心
    2020-11-22 09:35

    Here is a much simpler solution:

    function MyControl($scope){
        $scope.values = ["a","b","c","d","e","f"];
        $scope.selectedIndex = -1;
        
        $scope.toggleSelect = function(ind){
            if( ind === $scope.selectedIndex ){
                $scope.selectedIndex = -1;
            } else{
                $scope.selectedIndex = ind;
            }
        }
        
        $scope.getClass = function(ind){
            if( ind === $scope.selectedIndex ){
                return "selected";
            } else{
                return "";
            }
        }
           
        $scope.getButtonLabel = function(ind){
            if( ind === $scope.selectedIndex ){
                return "Deselect";
            } else{
                return "Select";
            }
        }
    }
    .selected {
        color:red;
    }
    
    
    • {{value}}

    Selected: {{selectedIndex}}

提交回复
热议问题