YStaum
YStaum

Reputation: 69

Ng-click affecting an ng-class

I attempted a 5 star rating system. Here is a simplified version my code: https://codepen.io/ystaum/pen/NWbLoPO

HTML:

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<body ng-app="app">
    <div ng-controller="Controller as ctrl">
      <div ng-repeat="star in ctrl.range" ng-init="rated = star.id">      
        <button ng-repeat="num in [1,2,3,4,5]" ng-class="{'blue':num <= rated}" ng-click="rated = num">{{ num }}</button>   
        </div>
      </body>

CSS:

 .blue{
        background:blue;
    }

JS:

(function () {

    angular
        .module("app", [])
        .controller("Controller", function ($http) {
            var vm = this;
      
            init();

            function init() {
                vm.rating = 3;
                
                vm.range = [{id:4},{ id:5},{id:0},{id:3}];
            };
        });
})();

The problem is that if you click on any button, just that button 'highlights' (if was not before). The way I set up the ng-class on the button should affect all buttons in that row (lower numbers 'highlighted, higher numbers not). Why is this not doing that? How do I make it do what I want?

Edited: The reason i used a var, was so i can keep the id value consistent, andto have the rating system show your choice in rating.

Upvotes: 0

Views: 36

Answers (1)

Moufeed Juboqji
Moufeed Juboqji

Reputation: 700

You don't need to initialize [rated] var

try

 <div ng-repeat="star in ctrl.range" >      
        <button ng-repeat="num in [1,2,3,4,5]" ng-class="{'blue':num <= star.id}" ng-click="star.id = num">{{ num }}</button>   
   </div>

Upvotes: 1

Related Questions