Executing ng-show function in Angular.js after the scope has been updated

I have a survey application, where users can participate in polls by voting for different options. Within the HTML template, I utilize ng-show to display whether a user has voted for a particular option in a poll or if it remains unvoted for the user:

<div data-ng-repeat="option in poll.poll_options" class="list-group-item">

    <span data-ng-if="option.option_thumb == '2'" class="glyphicon glyphicon-thumbs-up"></span>
    <span data-ng-if="option.option_thumb == '1'" class="glyphicon glyphicon-thumbs-down"></span>

    <div data-ng-show="optionVoted(option,authentication.user._id)">
            <span data-ng-bind="option.option_text"></span>
    </div>
    <div data-ng-hide="optionVoted(option,authentication.user._id)">
        <div data-ng-show="pollVoted(poll._id,votes)">
            <a data-ng-click="updateVote()">
                <span data-ng-bind="option.option_text"></span> - update
            </a>
        </div>
        <div data-ng-hide="pollVoted(poll._id,votes)">
            <a data-ng-click="createVote(poll,option,authentication.user._id,$index)">
                <span data-ng-bind="option.option_text"></span> - new
            </a>
        </div>
    </div>

    <span class="option-votes"> - {{option.votes.length}}</span>

</div>

The functions mentioned above are used to determine if the option/poll has been voted on by the user:

// Check if option is voted
    $scope.optionVoted = function(option,userId){
        for (var i = 0; i < option.votes.length; i++){
            if (option.votes[i].user === userId){
                return true;
            }
        }
};

// Check if poll is voted
$scope.pollVoted = function(pollId,votes){
    for (var i = 0; i < votes.length; i++){
        if (votes[i].poll === pollId){
            return true;
        }
    }
}

Here is the function used to create a new vote:

// Create a vote
$scope.createVote = function(poll,option,userId,index){

    var vote = new Votes({
        user:userId,
        poll:poll._id,
        poll_option:option._id
    });

    vote.poll_option_id = option._id;
    vote.$save(function(vote){
        option.votes.push(vote);
        $scope.$apply();
    }, function(errorResponse) {
        $scope.error = errorResponse.data.message;
    });
 }

When a user votes on an option, it gets updated without showing an anchor tag anymore. The challenge now is to ensure that other options within the poll also get updated and show "update()" instead of "create()", all without refreshing the page.

How can I make sure that the HTML DOM elements representing other options in the poll get updated?

Answer №1

To enhance your HTML code, consider switching out the functions within ng-show with an object property:

For instance, use ng-show="option.voted".

Remember to adjust the value of option.voted in the createVote function.

(Don't forget to customize this based on userId, etc.)

Answer №2

Ensure that you are properly updating the relevant object in your scope when recording a new vote. It appears that you are rendering information from $scope.poll.poll_options on your screen, but you are actually appending data to options.votes within your createVote function.

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

Can you identify the issue in this code?

I am facing an issue with using this code to save values in a table when the page loads. The function that searches for values is written in PHP, and I need to use these values in my script. Unfortunately, the current approach I am trying doesn’t seem ...

Retrieving the value of an array from a JSON data structure

I am working with the object shown below to extract the desired output. The result will be a new object that represents the final output. var data = { Customer: { Name: "emp1", Departments: [ {Departme ...

Cannot chain promises using 'then'

Having trouble understanding why the 'describeDir' promise chain is not working properly. Can anyone help me figure out what I did wrong here? Everything in the code seems to run, but functions like then or finally from the promise API never get ...

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

Having trouble with selecting JS dropdown options in Python Selenium

My HTML view- Check out the website design HTML code- View the HTML code here When I click on the dropdown arrow, a new code appears - view the code snippet Although my code successfully displays the dropdown options, it does not allow for selecting an ...

What techniques can be applied with Three.js to create terrain with voxel generators?

I came across voxel js, but it appears to be outdated and utilizes node js, which I am not interested in using. My goal is to generate basic terrain using for loops and a function to build a block. Below is the function I have created: function createBlo ...

Merging ng-if conditions

I would like to find a way for my two ng-if conditions to work together instead of separately. I want to display only the last one if both are true. Currently, this is how my code looks: <div> <img ng-src="{{img(myColor)}}" ng-if="myColor" ...

Is there a way for multiple controllers to share a single template using controllerAs syntax?

Assume there are two controllers defined as follows: function MainController() { this.hello = function() { // does something } } function AnotherController() { this.hello = function() { // does something else } } The controllerAs for Mai ...

The checkbox within the modal popup is failing to trigger the mousedown event on the external popup button

In the world of Drupal, there exists a unique phenomenon known as the modal popup - essentially a dialog box that appears within an iframe. One user found themselves faced with the challenge of triggering a mousedown event on a submit button located outsid ...

Step-by-step guide for setting up CodeMirror

I'm feeling a bit lost with what to do next: <link rel="stylesheet" href="lib/codemirror.css"> <script src="lib/codemirror.js"></script> <script> var editor = CodeMirror.fromTextArea(myTextarea, { mode: "text/html" }); ...

Oops! An error has occurred with the module in angular1

I recently integrated ui-router into my Angular 1 application and set up the route state. However, I encountered an error when trying to access the page mentioned in the title of this post. Below is the code snippet for reference. Can anyone point out wher ...

Can data be transferred from one website to another without the use of an API?

I am a newcomer to the world of web development with basic knowledge of JS, Node, Express, Mongoose, and MongoDB. I have an exciting idea for a web application that would function like a spreadsheet, gathering user inputs to generate an output. The unique ...

What is the best way to emphasize a table column when a cell is selected?

I successfully implemented a feature where a cell (td-element) is highlighted when clicked by the user. However, I now want the entire column to be highlighted with the cell itself having a slight variation. I am struggling with achieving the last part ...

Managing asynchronous tasks that do not save their outcomes within the application state

Upon discovering a requirement within a vanilla JS webapp that necessitates a single JSON "definitions" object for rendering, I realized that the definitions are to be loaded through an HTTP request at the start, then read, parsed, and passed down to anoth ...

Utilize dropdown1 to dynamically populate dropdown 2 in AngularJS

Here is the HTML code snippet I am currently working with: <select ng-controller="category" ng-model="selectedTestAccount" ng-options="c.category for c in categories track by c.categoryID" ></select> <select ng-controller="subcategory" ng ...

What is the best way to transfer data from R to JS in a Shiny app and incorporate it into the user interface?

I am looking to add a custom news button to the header of my shinyapp, which will display information from a specific dataset. I want the button to show the number of news items available, similar to how shinyDashboard::notificationItem() works but with mo ...

Edge is experiencing a slowdown when utilizing ng-bind-html

I've been using ng-bind-html to bind HTML content to a div element. However, when I attempt to bind larger amounts of HTML, it can take around 5-6 seconds for the content to load. Interestingly, this issue seems to only occur in Chrome browser. I have ...

"Pushing elements into an array does not function properly within a promise

I'm having trouble with my code - the push method isn't working and it's not returning anything. import {nearbyUsers, getLatitude, getLongitude} from './helper' const users = [] nearbyUsers(session, getLatitude(), getLongitude()).t ...

Is it considered good or bad practice to use plain JavaScript objects in an AngularJS application?

Imagine needing a custom object that doesn't rely on AngularJS (such as a specific collection with unique functionalities). You could create it independently of AngularJS and simply use it in services/controllers. Alternatively, you could design it a ...

Error encountered with the OffsetWidth in the Jq.carousel program

I am encountering an issue that I cannot seem to figure out. Unexpected error: Cannot read property 'offsetWidth' of undefined To view the code in question, click on this link - http://jsfiddle.net/2EFsd/1/ var $carousel = $(' #carouse& ...