1

My select dropdown, needs the class of btn-success if 2 variables form a JSON object != null.

What I've tried so far which isn't working, basically if term.tag and term.id are not null, add the class btn-success to the select.

This is inside of an ng-repeat term in terms is the JSON data.

<select ng-class="{ 'btn-success': term.tag != null && term.id != null }">
    <option value="companies">companies</option>
    <option value="news">news</option>
    <option value="people">people</option>
    <option value="products">products</option>
</select>

How would you go about this?

4
  • 5
    You should create a function in your controller to update a variable. Too much logic in your view is a bad thing. Commented Mar 17, 2015 at 21:17
  • 2
    Depends on what your term.tag is. Try just term.tag && term.id. Commented Mar 17, 2015 at 21:17
  • isherwood is right. Create a controller function and have it return the class you want right into ng-class. Commented Mar 17, 2015 at 21:21
  • @dfsq oh thanks! Yeah that is better, do you want to post an answer? Btw I found this which reads better too <select ng-class="term.tag && term.id ? 'btn-success' : 'btn-default'"> To left of : is if true, to right of : is false. Commented Mar 17, 2015 at 21:22

1 Answer 1

2

Change your HTML to something like this:

<select ng-class="getButtonClass()">

And add a function in your controller:

$scope.getButtonClass = function() {
    if (term.tag && term.id) {
        return 'btn-success';
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I could see that working for 1 example, however I have several hundred widgets which all contain the same select and generated on the page via an ng-repeat term in terms. Seems like there may be more involved in that case?
You'd probably pass in scope or some other indicator.
Oh yeah thanks! like... <select ng-class="getButtonClass(term.tag, term.user_id)">
I think this is a bad idea. The function will get evaluated multiple times per second!
Well, 9 years later it's just a bad idea to still be using AngularJS (Angular 1).

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.