0

I would like to set a class for an element using ng-click. However although ng-click sets the value correctly it can't be picked up on the same element using ng-class:

 <button class="button"  ng-click="selected=2;"  ng-class="{active:selected==2}"> </button> 

The above code would change the value for $scope.selected but ng-class can only seem to pick this up if it is set by the ng-click of another element.

0

3 Answers 3

1

try it like this

<button class="button"  ng-click="selected=2"  ng-class="{'active':selected==2}"> </button>
Sign up to request clarification or add additional context in comments.

Comments

1

The code is working fine. Here is a working fiddle so that you can check out where you getting it wrong.

Working Fiddle

Code snippet:

<button class="button"  ng-click="selected=2"  ng-class="{active:selected==2}">Click to add class </button>

Comments

1

For good measure, separate your assignments from the view into the controller.

Controller:

app.controller('ctrl', function () {

  $scope.select = function (index) {
    $scope.selected = index;
  };

  $scope.isSelected = function (index) {
    return $scope.selected === index;
  };

});

Markup:

<button class="button" ng-click="select(2)" ng-class="{ 'active': isSelected(2) }">

JsBin: http://jsbin.com/cajubixu/1/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.