0

I have for example variable 5 which I described in scope, I did range which calculating around this variable, now I have to show this variable and set the css.class for this variable. How can I do that?

this my example in code fiddle

Anton
  • 788
  • 4
  • 14
  • 34
  • Could you specify how do you want to "add css to a variable"? Probably you'll have to use ng-class, but what are you trying to achieve? – Keammoort Dec 10 '15 at 16:46
  • I'm trying to achieve that my variable was marked at other color, in example from fiddle, we see range from 0 to 9 with step 3, so we can see 0,3,6,9. I want to see my variable 5 and for example it was in a red color. – Anton Dec 10 '15 at 16:52

1 Answers1

2

Create a function that returns your preferred css class based on a value:

$scope.getClass = function(n) {
    /*example implementation*/
    if (n == 5) {
        return "red";
    } else {
        return "normal";
    }
  };

then inside ng-class property use this function:

<li ng-repeat="n in range(5,15)" ng-class="getClass(n)">test {{n}}</li>

jsfiddle

UPDATE:

Using your suggestions I've modified my solution. You can solve your problem like this: Let's assume you have a value set in your scope:

$scope.myvalue = 5;

then inside range function you'll have to add your value (it can be at the end):

$scope.range = function(min, max, step){
    step = step || 1;
    var input = [];
    for (var i = min; i <= max; i += step) input.push(i);
    input.push($scope.myvalue); //insert value that has to be highlighted
    return input;
  };

Then the array before you pass it to ng-repeat:

<li ng-repeat="n in range(0, 9, 3) | orderBy:identity" ng-class="{'red' : n == myvalue}">test {{n}}</li>

and add this to controller (so that orderBy work):

$scope.identity = angular.identity;

or if you're using AngularJS above 1.3.0-rc5 you can simply use (without entity declaration) (see related answer):

<li ng-repeat="n in range(0, 9, 3) | orderBy" ng-class="{'red' : n == myvalue}">test {{n}}</li>

See that in this case you don't need getClass() function anymore - you can just compare n to myvalue.

fiddle with new solution

Community
  • 1
  • 1
Keammoort
  • 3,075
  • 15
  • 20
  • definitely good idea but I have that range was calculated by my way, so we should see the range 0,3, 5(in red color),6,9. But I like you idea, I'll try to play with it – Anton Dec 10 '15 at 17:07
  • 1
    @Anton so you want to have an extra entry with your variable's value although it's not in array returned by range() function? – Keammoort Dec 10 '15 at 17:12