1

I would like to use the following jQuery from angular:

jQuery.prototype.stars = function() {
  return $(this).each(function() {
    var val = parseFloat($(this).html());      
    var size = Math.max(0, (Math.min(5, val))) * 16;
    var $span = $('<span />').width(size);
    $(this).html($span);
});
}

$(function() {
    $('span.stars').stars();
});

The code is copied from here: Turn a number into star rating display using jQuery and CSS

It seems it should be added in a directive, something like this:

link: function ($scope, elem, attrs) {     
    angular.element(document).ready(function () {
    $('span.stars').stars()
...

but I am not sure how to rewrite the function stars() jQuery has been extended with (jQuery.prototype.stars). Thanks so much for your help!

Community
  • 1
  • 1
Maksim
  • 33
  • 5

1 Answers1

0

It looks like all that jQuery function is doing is replacing the number with a <span></span> tag with a width based on the number contained in the tag. I would suggest just making the function a part of the directive, and refactor it for angular, something similar to this:

link: function($scope, elem, attrs) {
 function starify() {
    var val = parseFloat(angular.element(elem).html());
    var size = Math.max(0, (Math.min(5, val))) * 16;
    var span = angular.element('<span/>').css('width', size+'px');
    angular.element(elem).html(span[0].outerHTML);
 }
 starify();
}

This is using angular's base element provider(jQlite). There is no need to wait for the document to be ready.

Here is a super simple plunker: https://plnkr.co/edit/1N5PbN?p=preview

Pop-A-Stash
  • 6,572
  • 5
  • 28
  • 54