0

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>
3
  • if it works it works. I know that seems like a useless answer, but to me this looks like it would work Commented Jun 16, 2015 at 18:41
  • thanks.. @SirNeuman i'm an angular newbie so i'm always unsure :) Commented Jun 16, 2015 at 18:45
  • Than check AngularJS Tutorial: A Comprehensive 10,000 Word Guide from my updated answer. Commented Jun 16, 2015 at 19:19

2 Answers 2

1

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.

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

Comments

0

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'  
}

2 Comments

thanks, but i'll pull up the data from a rest api.. but i get your point
@teddybear123 are you looking for something more...I think its better to accept one of our answer..what are you waiting for?

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.