AngularJS using a function in ng-class to conditionally set classes

1.9k views Asked by At

i'm implementing a rating feature in my ionic app. i created icon fonts so i could display the the stars as classes. I want to use the ngclass directive to conditionally set what the class is based on the rating.

for my question: Is my Logic and Syntax correct??

/* MODEL */

$scope.items = [{id: 1, name: 'foo', rating: 3 },{id: 2, name:'bar', rating: 4}] 

...

/* CONTROLLER */

$scope.checkRating = function(rating) {

         if (rating === 1){ return 'one-star' }
    else if (rating === 2){ return 'two-star' }
    else if (rating === 3){ return 'three-star' }
    else if (rating === 4){ return 'four-star' }
    else if (rating === 5){ return 'five-star' }        

}

...

/* VIEW */

<ion-list>
  <ion-item ng-repeat="item in items">
    <h2>{{item.name}}</h2>
    <p><span ng-class="checkRating(item.rating)"></span><p>
  </ion-item>
</ion-list>
2

There are 2 answers

0
bpiec On BEST ANSWER

pankajparkar's answer is good but please consider following Angular JS best practices and avoid $scope syntax. Instead use controllerAs.

Also, John Papa's style guide is a very good source of good practices and you can learn much from it.

If you are new to AngularJS than I also recommend you to read AngularJS Tutorial: A Comprehensive 10,000 Word Guide by Todd Motto ‒ really worth to read.

2
Pankaj Parkar On

Rather than making conditional logic, I'd prefer to add class in JSON

Markup

<ion-list>
  <ion-item ng-repeat="item in items">
    <h2>{{item.name}}</h2>
    <p><span ng-class="item.class"></span><p>
  </ion-item>
</ion-list>

Code

$scope.items = [{id: 1, name: 'foo', rating: 3, class: 'one-star' },
              {id: 2, name:'bar', rating: 4, class: 'two-star'}] ;

OR

Create a array with having the mapping of rating and ids and use it on html.

HTML

<p><span ng-class="$scope.ratings[item.rating]"></span><p>

Markup

$scope.ratings = {
    "1":'one-star',
    "2":'two-star',
    "3":'three-star',
    "4":'four-star',
    "5":'five-star'  
}