javascriptcssangularjsangularjs-ng-clickangularjs-ng-class

How to set the ng-class in order of item clicked?


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

I have these 3 border classes:

.border1 {
  border: 1px solid #66FFFF;
}

.border2 {
  border: 1px solid #33CCFF;
}

.border3 {
  border: 1px solid #0099FF;
}

I want the first button that is clicked to gain the border1 class, 2nd button clicked the border2 class and same for border3.

Also I will eventually have code that prevents the user from selecting more than 3 buttons, so the user will only be able to select 3 buttons.

Current markup logic:

<div class="tag"
     ng-class="{'border1':selected1, 'border2':selected2, 'border3':selected3}"
     ng-mouseover="showTagDetails(t)"
     ng-click="clickTag(t)">{{t.name}}</div>

However, I'm unsure as how to write the logic to ensure that the 2nd and 3rd buttons gain the appropriate styles. How would one approach this problem?

$scope.clickTag = function(t) {

}

Solution

  • You could use $index here to mainatain a list of selected index.

    Markup

    <div class="tag-container">
        <div class="tag" ng-class="selected.indexOf($index)!== -1 ? 'border'+ (selected.indexOf($index) + 1): ''" 
         ng-mouseover="showTagDetails(t)" ng-click="clickTag($index)">
            {{t.name}}
        </div>
        <tag-details tag="t"></tag-details>
    </div>
    

    Code

    $scope.clickTag = function(index) {
      //first check length and then restrict duplicate index,
      if ($scope.selected.length < 4 && $scope.selected.indexOf(index) === -1) {
        $scope.selected.push(index);
      }
    }
    

    Plunkr Demo