2016-08-08 2 views
2

응답에 따라 동적으로 별표 평점을 표시해야합니다.응답에 따라 동적으로 별표를 표시하는 방법은 무엇입니까?

1에서 5까지의 값을 표시 할 수 있지만 등급이 0이면 빈 별이 표시되지 않습니다.

등급 = 0.4 인 경우 1 개의 별표도 표시됩니다.

내 컨트롤러 :

(function() { 
    'use strict'; 


    angular 
    var app = angular 
     .module('app') 

app.directive('starRating', function() { 

    return { 
     restrict: 'A', 
     template: '<ul class="rating">' + 
      '<li ng-repeat="star in stars" ng-class="star" ng-click="toggle($index)">' + 
      '\u2605' + 
      '</li>' + 
      '</ul>', 
     scope: { 
      ratingValue: '=', 
      max: '=' 
     }, 
     link: function (scope, elem, attrs) { 

      var updateStars = function() { 

       scope.stars = []; 
       for (var i = 0; i < scope.max; i++) { 
        if(i == 0) { 
         scope.stars = []; 
         scope.stars.push({ 
         empty: i = 0 
        }); 
        } else { 
        scope.stars.push({ 
         filled: i < scope.ratingValue 
        }); 
        } 
       } 

      }; 
      scope.$watch('ratingValue', function (oldVal, newVal) { 
       if (newVal) { 
        updateStars(); 
       } 
      }); 
     } 
    } 
}); 


app.controller('Controller', Controller); 

    Controller.$inject = ['UserService', '$location', '$rootScope', '$scope', 'fileUpload', 'FlashService', '$cookieStore', '$timeout', '$window']; 

    function Controller(UserService, $location, $rootScope, $scope, fileUpload, FlashService, $cookieStore, $timeout, $window) { 

$scope.selectTestSubject = function() { 

$scope.rating = 0; 

    console.log(levels.length); 

     for(var k=0; k<levels.length; k++) { 
      var respRating = levels[k].rating; 
//   var respRating = 1.5; 

      console.log(respRating); 

      $scope.ratings = [{ 
       current: respRating, 
       max: 5 
      }]; 

      if(respRating == 0) { 

       $scope.defaultRating = true; 
      } else { 

       $scope.defaultRating = false; 
      } 
     } 
    } 
    } 
})(); 

내 HTML 페이지 : 솔루션과

<div><span ng-repeat="rating in ratings"> 

     <div star-rating rating-value="rating.current" max="rating.max"></div> 
     </span> 
    </div> 
+1

'등급이 0이면 비어있는 별이 표시되지 않습니다. '등급이 0 인 경우 표시 할 시작 횟수는 몇 개입니까? –

+0

for (var i = 0; i gyc

+0

최대 값 = 5 즉, 별표 없음 = 5를 사용하고 있습니다. 등급 = 0이면 별표가 표시되지 않는 대신 5 개의 별표가 표시되어야합니다. @ Raman Sahasi – kalai

답변

2

하나의 문제는 $ 시계 표현이다. 다음이 여기서

scope.$watch('ratingValue', function (oldVal, newVal) { 
    if (newVal) { 
     updateStars(); 
    } 
}); 

oldValnewVal 실제로 주위 잘못된 방법은 $ 시계 함수는 먼저 이전 값 다음에 새로운 가치에 걸립니다. 둘째, 0은 허위 값이기 때문에 if (newVal) 조건은 0에 대해 작동하지 않습니다.

대신이 있어야합니다

scope.$watch('ratingValue', function(value, previousValue) { 
    // Only update the view when the value has changed. 
    if (value !== previousValue) { 
     updateStars(); 
    } 
}); 

귀하의 updateStars 기능은 항상 scope.stars 변수를 reinitialises과에 추가합니다. 이렇게하면 원하지 않는 부작용이 생길 수 있으며보기에 모델 값이 반영되지 않습니다. 배열을 초기화 한 다음 항목이 아직없는 경우 추가하거나 기존 값을 업데이트하는 것이 가장 좋습니다. 은 $ 시계 표현은 별을 업데이트하기 때문에 값이 변경되면, 당신은 지금 업데이트 처음으로 귀하의 링크 기능 화재 트리거해야합니다

// Initialise the stars array. 
scope.stars = []; 

var updateStars = function() { 

    for (var i = 0; i < scope.max; i++) { 
     var filled = i < Math.round(scope.ratingValue); 
     // Check if the item in the stars array exists and 
     // append it, otherwise update it. 
     if (scope.stars[i] === undefined) { 
      scope.stars.push({ 
       filled: filled 
      }); 
     } else { 
      scope.stars[i].filled = filled; 
     } 
    } 

}; 

: 그래서 당신이 뭔가를해야합니다. 그래서 이것은 단순히 그래서 같은

// Trigger an update immediately. 
updateStars(); 

올바르게 스타에 filled 속성을 사용하지 않습니다 또한 귀하의 템플릿, 대신 포함해야 적절한 ng-class : 간단한 스타일

<ul class="rating"> 
    <li class="star" 
     ng-repeat="star in stars" 
     ng-class="{ filled: star.filled }" 
     ng-click="toggle($index)"> 
     \u2605 
    </li> 
</ul> 

,

.star { 
    cursor: pointer; 
    color: black; 
} 

.star.filled { 
    color: yellow; 
} 

mouseentermouseleave effe를 듣고이 등급 시스템을 개선 할 수도 있습니다. cts이므로 사용자가 새 값을 선택하면 별이 노란색으로 표시됩니다. 이것은 꽤 일반적인 기능입니다. 몇 가지 수정을 통해이를 달성 할 수 있습니다.템플릿이 이벤트를 수신하도록 업데이트해야합니다 우선

:

<ul class="rating"> 
    <li class="star" 
     ng-repeat="star in stars" 
     ng-class="{ filled: star.filled }" 
     ng-mouseenter="onMouseEnter($event, $index + 1)" 
     ng-mouseleave="onMouseLeave($event)" 
     ng-click="toggle($index)"> 
     \u2605 
    </li> 
</ul> 

다음으로, 우리는 updateStars에 작은 조정을 만들고 싶어은 평가 매개 변수에 걸릴 기능 :

var updateStars = function(rating /* instead of blank */) { 

    for (var i = 0; i < scope.max; i++) { 
     var filled = i < Math.round(rating); // instead of scope.ratingValue 
     // Check if the item in the stars array exists and 
     // append it, otherwise update it. 
     if (scope.stars[i] === undefined) { 
      scope.stars.push({ 
       filled: filled 
      }); 
     } else { 
      scope.stars[i].filled = filled; 
     } 
    } 

}; 

// Trigger an update immediately. 
updateStars(scope.ratingValue /* instead of blank */); 

scope.$watch('ratingValue', function(value, previousValue) { 
    // Only update the view when the value changed. 
    if (value !== previousValue) { 
     updateStars(scope.ratingValue /* instead of blank */); 
    } 
}); 

이제 우리는 뷰에서 우리의 이벤트 콜백에

// Triggered when the cursor enters a star rating (li element). 
scope.onMouseEnter = function (event, rating) { 
    updateStars(rating); 
}; 

// Triggered when the cursor leaves a star rating. 
scope.onMouseLeave = function (event) { 
    updateStars(scope.ratingValue); 
}; 

을 추가 할 수 있습니다 그리고 내가 있어요 티! Full demo here.

+0

이것은 좋은 답변입니다, 작성 시간을내어 주셔서 감사합니다! 죄송합니다. 당시 회신을받지 못했습니다. 나는 보상으로 며칠 만에 작은 현상금을 보낼 것입니다. – halfer

+0

당신은 너무 친절 해요! 고마워요. 정말 고마워요. :) –

+0

환영합니다. 모니카, 더 많이 똑같아주세요. ':-)' – halfer

관련 문제