4
\$\begingroup\$

I want to apply a different badge color with bootstrap depending on a number.

I wrote a filter to accomplish this...

angular.module('Demo')
    .filter('reserveStatus', function() {
        return function(num) {
            var klass = "";

            num = parseInt(num, 10);

            if (num > 2 && num < 5) {
                klass = "alert-success";
            }                    
            else if (num >= 5 && num < 10) {
                klass = "alert-warning";
            }
            else if (num >= 10) {
                klass = "alert-danger";
            }

            return klass;
        }
    });

And it's used with interpolation like this...

<span class="badget {{reserve.qty | reserveStatus}}"></span>

Is this a good way to accomplish this?

\$\endgroup\$
2
\$\begingroup\$

Fun question, I think this is okay.

I would name klass -> class and I would consider building a map for the values:

var classMap = [
  { from : 3 , to : 5       , class : 'alert-success' },
  { from : 5 , to : 10      , class : 'alert-warning' },
  { from : 10, to : Infinity, class : 'alert-danger'  }
];
\$\endgroup\$
  • 1
    \$\begingroup\$ I believe it is best practice to avoid using class as it is a reserved keyword for ECMAScript 6 (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…). \$\endgroup\$ – threed Aug 19 '14 at 20:55
  • \$\begingroup\$ Extremely good point! +1 comment. It is though okay to use class as a property of an object according to JsHint, not so much as a variable name. \$\endgroup\$ – konijn Aug 19 '14 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.