How can I retrieve the rating value in AngularJS Bootstrap after submitting a form?

I successfully incorporated the bootstrap star rating feature in an angularjs project. Although everything is functioning properly, I am encountering an issue with retrieving the final rating value after submitting the form. Below is the code snippet:

 // JavaScript code
 angular.module('plunker', ['ui.bootstrap']);

var RatingDemoCtrl = function ($scope) {

     $scope.submit = function() {
         console.log($scope.overStar); // always returns null
     }

     $scope.rate = 1;
     $scope.max = 5;
     $scope.isReadonly = false;

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

// HTML code
<!doctype html>
<html ng-app="plunker">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
    <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">

</head>
<body>
<div ng-controller="RatingDemoCtrl" class="well well-small">
<form class="Scroller-Container" ng-submit="submit()" >

    <rating value="rate" max="max" readonly="isReadonly" on-hover="hoveringOver(value)" on-leave="overStar = null" ></rating>
    <span class="badge" ng-class="{'badge-warning': percent<30, 'badge-info': percent>=30 && percent<70, 'badge-success': percent>=70}" ng-show="overStar && !isReadonly">{{percent}}%</span>

</div>
<input type="submit" id="submit" value="Submit" />
</form>
</body>
</html>

Despite attempting to use ng-click to set the value, it does not trigger for some unknown reason. Has anyone encountered this issue before and can provide assistance? Thank you.

Answer №1

Implement the hoveringLeave method.

Below is the corrected code:

JS

 angular.module('plunker', ['ui.bootstrap']);

var RatingDemoCtrl = function ($scope) {

    $scope.myRate = 0;

     $scope.submit = function() {
         console.log($scope.percent) ; 
     }

     $scope.rate = 1;
     $scope.max = 5;
     $scope.isReadonly = false;
     $scope.percent = 20;

      $scope.hoveringOver = function(value,object) {
        console.log('hoveringOver', value);
        $scope.overStar = value;
        $scope.percent = (100 * $scope.overStar) / $scope.max;
      };

       $scope.hoveringLeave = function(rate) {
         console.log('hoveringLeave',  $scope.rate);

       $scope.percent = (100 * $scope.rate) / $scope.max;
      };
    };

HTML

<form class="Scroller-Container" ng-submit="submit()" >
    <rating  value="rate" max="max" readonly="isReadonly" on-hover="hoveringOver(value)" on-leave="hoveringLeave(rate)" ></rating>
    <span class="badge" ng-class="{'badge-warning': percent<30, 'badge-info': percent>=30 && percent<70, 'badge-success': percent>=70}" ng-show="overStar && !isReadonly">{{percent}}%</span>

<input type="submit" id="submit" value="Submit" />
</form>

Demo Plunker

Answer №2

The issue with $scope.overStar always returning null when submitted is due to the 'on-leave="overStar = null"' in your html code. This causes $scope.overStar to be set to null whenever your mouse leaves that area.

It is important to note that merely moving your mouse away does not necessarily mean that a user has selected a rating. This distinction is crucial because setting it up this way could result in more ratings being recorded than necessary.

Answer №3

In my current project, I am utilizing Angular version 1.2.* along with UI Bootstrap 0.10.0. The ng-click functionality is working seamlessly for me:

My HTML Code:

<rating value="rate" max="5" ng-click="save(rate)"></rating>

Controller Logic:

$scope.save = function (score) { console.log('Rating: ', score); };

Answer №4

Instead of incorporating an additional button, my recommendation would be to utilize a $watch function on the rate within the scope to monitor for any changes in value.

$scope.$watch('rate', function(newValue, oldValue) {
    if(newValue !== oldValue){
        alert(newValue + ' ' + oldValue);
    }
});

If this scenario arises, you can then save the new modification.

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

Enhance your AJAX calls with jQuery by confidently specifying the data type of successful responses using TypeScript

In our development process, we implement TypeScript for type hinting in our JavaScript code. Type hinting is utilized for Ajax calls as well to define the response data format within the success callback. This exemplifies how it could be structured: inter ...

The usage of the enzyme shallow() function combined with the addition of event listeners

A specific component is causing some issues in my application: class ProblematicComponent extends Component { componentDidMount() { this.monitorForClicks(); } monitorForClicks() { this.elementRef.addEventListener('click', () => ...

Having trouble iterating through a JSON response in an Ember template

Here is the content of my JSON array: { "object": { "assignments": [ { "assignmentId": 14706368, "sectionId": 0, "assignmentTitle": "file attachment A", "assignmentSta ...

Error message: ReactJs is unable to read the property 'map' as it is undefined

After making an axios get request to a Yelp API, I successfully retrieved the data and logged 20 results in an object array. However, when attempting to map through the results, I encountered two errors in my console: app.js:53912 Uncaught TypeError: Can ...

If the camera position in Three.js is trapped within an if-else statement

I am working on enhancing the variability of camera positions in order to make the 3D scene more captivating. However, I am facing an issue where the camera gets stuck at -12, causing it to oscillate between 12.00 and 12.05 before finally moving beyond t ...

Utilize modules within the AppModule to promote modularization and maintain separation of concerns in Angular 2

When using templates like those from the ASP.NET Core JavaScript services, typically a single module named AppModule is included. However, in my application, which is divided into two logical areas (AreaA and AreaB), I thought it would be better to use two ...

Encountering an issue when using npm to add a forked repository as a required package

While attempting to install my fork of a repository, I encountered the error message "Can't install github:<repo>: Missing package name." The original repository can be accessed here, but the specific section I am modifying in my fork is located ...

There seems to be a mysterious issue with the addClass function in jQuery, as it is not behaving

I am facing an issue with the function showColorStart() as it is not working as expected. When this function is called, the background color of the squares should change to the color specified in the array colorspicked[lindex], but it is not doing so. I ha ...

The controller method fails to pass a value to the extended controller

There is a scenario where one controller extends another: I am looking to store the result of the second controller's method into a variable in the first controller First Controller: angular.module('Gestios').controller('EmpresasCont ...

Using AngularJS controller to implement filtering functionality

I am a beginner at using Angular and have successfully implemented a filter to translate text for localization in my HTML view: <input type="button" class="btn btn-link" value="{{'weeklyOrdersPage.reposting' | translate}}" ng-click="sortBy(&a ...

Regex pattern to replace the zero preceding two times within a string based on distinct criteria

I need to transform the string XY4PQ43 using regex in JavaScript. The output should be XY04PQ0043. Specifically, I want to add a zero prefix to the first number if it is a single digit to ensure it has 2 digits, and for the second number in the string, I w ...

Is it possible to receive both errors and warnings for the same ESLint rule?

My team is currently in the process of refactoring our codebase, utilizing ESLint to pinpoint any lint errors within our files. Initially, we set high thresholds in one .eslintrc file and have been gradually decreasing these limits as we enhance specific f ...

Obtain the texture from a user upload and apply it to a geometry in three.js

As a beginner in three.js and JavaScript, I am excited about the possibilities and have been creating small Three.js scenes to improve my skills. My ultimate goal is to build a 3D website, but I am currently stuck on how to allow users to upload an image f ...

Limit certain characters within special characters

I have experimented with a regular expression that matches strings containing zero or more occurrences of "%" and "&", but returns false if "@" or "$" is found: ^((%&)*(?!@).)*$ Now, I require a regex pattern to validate strings that must contain ...

Implementing requirejs alongside retinajs for enhanced performance and compatibility

Currently, I am utilizing a combination of requirejs and retinajs as a plugin. To ensure smooth functioning, I am incorporating the shim feature along with a jQuery dependency: .... 'plugins/retina.min': { 'deps': ['jquery ...

The accumulation of input using setInterval is not effective

I need some help with my code. Please take a look at this link here. I want the input to count up from zero and hide when I click the "change" button. But when I show the input again, I want its value to reset back to zero. Can anyone guide me on how to ...

JavaScript: abbreviated way to selectively append an element to an array

Currently, I am in the process of creating a Mocha test for a server at my workplace. When dealing with customer information, I receive two potential phone numbers, with at least one being defined. var homePhone = result.homePhone; var altPhone = ...

Can PDO prepared statements provide sufficient protection against SQL injection?

Is relying solely on PDO prepared statements enough to secure against MySQL-related security risks, or is it necessary to also perform server-side character validation? I am currently using PDO prepared statements and client-side JavaScript form checking, ...

How can I dynamically update HTML content in React upon receiving an AJAX response?

Hi there, I'm new to using React and I have a requirement where I need to make an AJAX GET request to the server when a user clicks on a button. Based on the received response, I need to prepare HTML and display it. I tried implementing this with the ...

Encountering a Installation Issue with Angular CLI on Ubuntu 20.04

When trying to install @angular/cli globally using the command sudo npm install -global @angular/cli, an error was encountered. The error message displayed warnings about deprecated libraries and an existing file that caused the installat ...