2

I am using Angular-UI and Bootstrap 3.

I have this HTML connected to a scope (assume the scope has a $scope.myBtn = "A", say).

<button type="button" class="btn btn-primary" ng-model="myBtn" btn-radio="A">A</button>
<button type="button" class="btn btn-primary" ng-model="myBtn" btn-radio="B">B</button>
<button type="button" class="btn btn-primary" ng-model="myBtn" btn-radio="C">C</button>

This produces three blue buttons, which is what I want. When one of the buttons is clicked, the $scope.myBtn value gets set to the right value (say, "B") and that button's class gets set to:

<button type="button"
  class="btn btn-primary active" ng-model="myBtn" btn-radio="B">B</button>

(notice the addition of active in the class).

When one button is active I want to remove the "btn-primary" class and add the "btn-success" class. I know I could do it this way (and it is what I am actually using now):

<button
  type      = "button"
  class     = "btn"
  ng-class  = "{
    'btn-primary': myBtn != 'B',
    'btn-success': myBtn == 'B'
  }"
  ng-model  = "myBtn"
  btn-radio = "'B'">B</button>

But that seems brutally verbose for every button... Is there some better way to do this?

1 Answer 1

3

You can use a directive to conditionally set the class by observing the model value

app.directive('myClass', function () {
    return {
        link: function (scope, element, attrs) {
            attrs.$observe('ngModel', function (item) {
                if (scope.myBtn !== 'B') {
                    attrs.$set('class', "btn-primary");
                } else {
                    attrs.$set('class', "btn-success");
                }
            });
        }
    }
});

Working Demo

Sign up to request clarification or add additional context in comments.

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.