AngularJS allows for setting the rate value using the jQuery Raty plugin

I am attempting to implement the jquery raty plugin for star rating using angularjs. To achieve this, I have created a custom directive as shown below:

app.directive("ngStars", function() {
        return {
            restrict: 'A',
            link: function(scope, elem, attrs) {
                $(elem).raty({ 
                   'path': base_url+'images',
                    score:  attrs.score,
                    readOnly: true,
                    hints: ['سىء جدا', 'سىء', 'عادى', 'جديد', 'ممتاز'],
                });
            }
        }
    });

Here is my html code:

<div ng-repeat="place in places">
    <div ng-stars class="star" score={{place.rate}}></div>
</div>

The plugin works when I manually set the score attribute value like score="5". However, I need to dynamically set the score value using angularjs with score="{{place.rate}}", but it's not functioning as expected.

How can I resolve this issue?

Answer №1

To link the template directive with the supplied scope value, follow these steps:

I've created a demo where you can utilize the $scope.rating option in a controller to modify the rating.

Check out the working demo here

template: '<ul class="rating">' +
              '<li ng-repeat="star in stars" ng-class="star">' +
                '\u2605' +
              '</li>' +
            '</ul>',
  scope: {
    ratingValue: '=',
    max: '='
  },
  link: function (scope, elem, attrs) {
    scope.stars = [];
    for (var i = 0; i < scope.max; i++) {
      scope.stars.push({filled: i < scope.ratingValue});
    }
  }

If you need more detailed explanations, this tutorial is highly recommended.

Answer №2

Experience the amazing features offered by UI Bootstrap, which includes a fantastic rating feature.

Check out the directive below:

<rating ng-model="rate" max="max" readonly="isReadonly" on-hover="hoveringOver(value)" on-leave="overStar = null"></rating>

And here is how you can implement it in your controller:

angular.module('ui.bootstrap.demo').controller('RatingDemoCtrl', function ($scope) {
  $scope.rate = 7;
  $scope.max = 10;
  $scope.isReadonly = false;

  $scope.hoveringOver = function(value) {
    $scope.overStar = value;
    $scope.percent = 100 * (value / $scope.max);
  };

  $scope.ratingStates = [
    {stateOn: 'glyphicon-ok-sign', stateOff: 'glyphicon-ok-circle'},
    {stateOn: 'glyphicon-star', stateOff: 'glyphicon-star-empty'},
    {stateOn: 'glyphicon-heart', stateOff: 'glyphicon-ban-circle'},
    {stateOn: 'glyphicon-heart'},
    {stateOff: 'glyphicon-off'}
  ];
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

a single function spread across two controllers[JavaScript]

My query pertains to a JavaScript program with 2 controllers. The issue I am facing is the need for one function in both controllers (data.duration). This function serves two purposes, once for features themselves and once for the summary. Currently, this ...

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

Automatically populate textboxes with database information based on selected combobox item without the need to refresh the page

I would like to implement a feature where textboxes are automatically filled from a database when a user selects an option from a combo box. This can be achieved using jQuery or JavaScript in PHP. Once a user selects an element, the corresponding text sh ...

I am looking to transmit an array through $.ajax and retrieve it within a traditional asp page

I am working with an array that contains the ids of cities collected from a select input field var city = $('select[name="city"] :selected').map(function(){return $(this).val();}).get(); My goal is to send this array to a classic ASP page, wher ...

Refreshed the page following a setAttribute function call in Javascript

I have successfully implemented a function to switch between light and dark mode on my webpage using VueJS. However, I am facing an issue with the code: <a @click="toggleTheme" class="switch-mode" href> <div class=&q ...

Encountering issues with the phaser framework while setting up a server on xampp, faced with errors in javascript and html

Recently, I've been working on a game using Phaser and encountered some issues while trying to run the code in XAMPP. The game's base is located at htdocs/itw/test.html, with the necessary pngs and json file stored in htdocs/itw/assets/. The pngs ...

Is Angular 2 hardcoded to all HTML tags?

As a beginner in Angular 2, I am struggling to understand whether Angular 2 recognizes all HTML tags. For instance, if I include <code></code> in a template, which is a valid HTML 5 element, there are no issues. However, if I change it to < ...

I am using JavaScript to randomly choose a function, but once it's selected, the code within it does not execute

I am attempting to randomly choose a function from an array that contains various functions. While the console is showing me the selected function as "[Function: cycle3]," the code within the chosen function is not being executed. How can I ens ...

The property for the JQuery keyboard event code is consistently null

Per information from MDN, keyboard events are supposed to have a code property that returns a string constant like "KeyA" if the A key has been pressed. However, in my JQuery keyup event handler, the code property always remains undefined: $(document).on( ...

Error message from Meteor-Now deployment: "sh: meteor command not found"

I'm encountering issues deploying my meteor app with meteor-now. I followed a tutorial here, and also attempted deployment using ZEIT's OSX Client, but I keep getting the same error. Is there a workaround that anyone can suggest? Edit 1: H ...

Combining Laravel with React

Currently in the process of developing a substantial real estate listings platform with react and laravel. Can you suggest which approach would be better for this project and explain why? Option 1: Implement laravel react presets and store all react compo ...

Error: The function m.easing[this.easing] is not defined

I have been working on creating anchor link scrolling and tooltip display using bootstrap, but I am encountering an issue. $(window).scroll(function(){ if ($(window).scrollTop() >= 100) { $('#header').addClass('fixed'); ...

Leveraging Enjoyhint within nextJS

I am attempting to create a code tour using EnjoyHint, but encountered an error after installing the xbs-enjoyhint library. The error reads: Server Error - ReferenceError: CanvasRenderingContext2D is not defined. This issue is within the jquery.enjoyhint ...

Issue with resetting input forms in ReactJS

I have a simple form that seems to be clearing the rest of the fields every time I try to fill it. Additionally, validation errors are being displayed below each field instead of just one. How can this issue be fixed? Here is how the form looks before any ...

How can you quickly track the AJAX requests being sent?

Is there a tool, preferably a Firefox extension, that can show me all AJAX subrequests? I want to be able to see the URL being requested and any GET or POST variables that are sent with it whenever an XMLHTTPRequest() is made. I haven't found anythin ...

Managing Flicker Effect by Implementing Theme Switching and Using Local Storage in Next.js with Ant Design

I've been working on a new feature to switch themes (light/dark) dynamically in a Next.js application using Ant Design. Successfully integrating the theme switch with a toggle switch and useState hook, I'm faced with the challenge of storing the ...

Create a line break in an alert using PHP

<?php function alert($msg) { echo "<script type='text/javascript'>alert('$msg');</script>"; } if(array_key_exists('btnRegisterAdmins', $_POST)) { $fname = $_POST['FirstName']; $lname=$_POST['La ...

Navigating to an API endpoint while iterating through an ng-repeat loop

I am currently working with an API that provides a list of values. My goal is to enable users to click on the name of a driver in the API and be directed to specific details related to that driver. However, I am struggling to figure out how to implement th ...

Displaying a certain div when clicked within a loop using Vue.js and Laravel

I am currently facing an issue with displaying a hidden div upon click. The problem arises when using a loop to dynamically generate all the divs. Whenever I click the button, it shows all the divs instead of just one specific div on each click. I attempte ...

Having difficulty accessing response data and headers within an AngularJS interceptor

I have a custom API on my server that sends a unique header (let's call it "customHeader") in response to http://localhost:8081/my/test/api. Currently, I am attempting to access this custom response header from an interceptor written in angularJS: an ...