Determine whether the ng-click button has already been clicked or not

Currently, I am toggling a div when the ng-click event is triggered using the isVisible variable. The issue I'm facing is that every time the button is clicked, the function $scope.Objectlist.push(data); is executed. My goal is to only push the data on the initial click, but also allow it to push if a different object is being fetched. Each row has a button next to it with a unique ID passed as a parameter to the button function.

HTML:

<tr ng-repeat="object in objectlist">
    <td>{{object.id}}</td>
    <td><button ng-click="pushData(object.id)">View</button></td>
</tr>

JS:

$scope.objectlist = [];
$scope.isVisible = false;
$scope.pushData= function(id) {
    $http.get("some variables being passed on here").success(function(data, status, headers, config){
            $scope.objectlist.push(data);
    }).error(function(data, status, headers, config){
        alert("Error");
    });
    $scope.isVisible = ! $scope.isVisible;
};

Since there are multiple objects, some empty and some not, the function cannot solely rely on the length of the list for its logic.

Answer №1

Have you considered storing visibility based on object id (I haven't tested this yet):

HTML

<tr ng-repeat="object in objectlist">
    <td>{{object.id}}</td>
    <td><button ng-click="pushData(object.id)">View</button></td>
</tr>

JS

$scope.objectlist = [];
$scope.isVisible = false;
var store = {}; // Store visibility (boolean) per object id

$scope.pushData= function(id) {
    // If not stored yet
    if (!store[id]) {
        $http.get("some variables being passed on here").success(function(data, status, headers, config){
            $scope.objectlist.push(data);
            store[id] = true; // Store it and set true for the visibility
        }).error(function(data, status, headers, config){
            alert("Error");
        });
    }
    $scope.isVisible = !store[id]; // Set the visibility depending on if the object is already in the store or not
};

I'm unsure about the $scope.isVisible = !store[id]; as I'm not familiar with its impact on the view. But a similar approach could be effective.

Answer №2

Consider this approach:

$scope.itemList = [];
$scope.isHidden = true;
var uniqueIds = {}; 

$scope.addData = function(id) {
    $http.get("passing some variables here").success(callbackFunction)
        .error(function(data, status, headers, config){
            alert("Error");
        });

    $scope.isHidden = !uniqueIds[id];
};

var callbackFunction = function(data){
    if(!uniqueIds[data.id]){
        $scope.itemList.push(data);
        uniqueIds[data.id] = true;
    }
};

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

Modify the content of an element upon hovering over a different element

I have a set of three buttons and I want the text displayed in a box to change based on which button is being hovered over. If no button is being hovered, the default text should be "See details here". Is there a more efficient way to achieve this function ...

Something isn't quite right - Mobile Compatibility not functioning

I have been developing a website and running into an issue with the header. It works fine on desktop and is responsive, but on mobile devices, the Bootstrap functionality seems to be missing. I've included my code below, could someone please help me i ...

How can I extract the value of a JavaScript variable using jsoup in an HTML document?

<html> <script type="text/javascript"> var map = null; jQuery(function($) { L.marker([50.065407, 19.945104], {title: 'Cat'}) .bindPopup('<h3>Cat</h3> ...

A specific div remains in place as the user scrolls

Imagine a div that is positioned 60px from the top of the screen. What if, as you scroll down, it stops when it reaches 10px from the top and remains there for the rest of your scrolling session? And then, when you scroll back up, it goes back to its ori ...

Leveraging jQuery within a method defined in an object using MyObject.prototype.method and the 'this' keyword

Recently, I've started exploring Object-oriented programming in JavaScript and have encountered a challenge. I'm trying to define an object like the example below, where I am using jQuery inside one of the methods. I'm curious about the best ...

Customize the CSS for MaterialUI's TablePagination's MenuItem

Having trouble figuring out how to override CSS for the child component MenuItem within TablePagination? Check out this link for more information: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TablePagination/TablePagination.j ...

Tips for optimizing character count for mobile web pages with varying screen sizes and font settings

As I embark on developing an eBook mobile app, I am faced with various considerations such as screen size, font size, and determining the number of paragraphs to include on a single page based on the current screen and font settings. My aim is to adjust t ...

What is the reason behind primitive values being duplicated when forming an array from them?

While working on this code snippet... public static void main(String[] args){ int x = 1; int y = 2; int[] z = new int[]{x, y}; z[0] = 3; System.out.println(x); //prints 1 } I was surprised that the output was 1 instead of 3. I believe ...

PHP - Extracting a specific value from an array based on its key

Can anyone assist me with retrieving the values of an associative array using its key? Here is the example array structure: $new = array( array( "post" => "anything", "newt" => "Nothing" ), array( "post" => "something", "newt" => "Filthy" ), ...

Is there a way to bypass the serialization and deserialization process for users in Passport.js?

Utilizing Passport.js and Angular for a web application, I aim to leverage Passport.js for authentication without the use of sessions. However, I consistently encounter an [Error: Failed to serialize user into session] each time I attempt to authorize a us ...

After the animation has finished, the ".animated" class should be removed. If the element is reloaded, the class should be added back using plain

Within my CSS, there is a ".animated" class that is automatically applied to all elements with the "drawer-wrapper" class. The HTML structure looks like this: <div class="drawer-wrapper animated"> foo </div> I created a function that ...

What is the best way to populate a div with multiple other div elements?

My current project involves creating a sketchpad using jQuery for an Odin Project assignment. However, I have encountered an issue with filling the canvas (wrapper div) with pixels (pixel divs). The canvas does not populate correctly. Here is the link to m ...

Creating arrays with dynamically allocated memory without using calloc or malloc

I am struggling to understand the process of declaring an array in this program: int main(){ int n; printf("Please enter the number of elements:"); scanf(" %d",&n); int items['n']; for(int i = 0; i < n; i++) { scanf(" %d", ...

What is the process for turning off caching in CORS-Anywhere?

Encountering an issue with CSRF token validation while making a POST request to an endpoint on a different server using cors-anywhere. The error occurs because the CSRF Token passed to the cors-server is cached, leading to validation failure. Referenced a ...

Why is my jQuery animation running so sluggishly everywhere? Is there a way to improve its performance and make

I attempted to replicate the slider effect seen on this website: Below is the animation code: $('.tagLink').click(function () { $('html').css('overflow', 'hidden'); $('#tagBoxOverlay&ap ...

Regarding the pointer arrays

Currently, I am watching a tutorial video by Bucky on YT that explains heap. #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <math.h> int n, howMany; int total; float average = 0.0; in ...

When jQuery is used to move rows between tables, it can interfere with

When moving rows between tables, everything seems to work fine. However, once the row is moved to the other table, all JavaScript functions related to that row stop working, and the reason remains unknown. The JavaScript code is simple - it involves takin ...

Load and unload stylesheets on the fly dynamically

After searching through numerous posts and forums without success, I am in need of a solution to dynamically load and unload stylesheets for my website. The website I am constructing has a main stylesheet along with 2 optional stylesheets that alter color ...

Converting IP addresses and ports into an array structure

I have a list of IP addresses in the format 127.0.0.1:80. Is there a simple way to convert this list into an array that looks like this? array( array('1.179.197.9', '88080'), array('1.234.45.50', '3128'), ...

Exploring the process of integrating and registering local components within the App.vue file

Currently, I am working with Laravel 10, Vite, and Vue I would like to incorporate two components into my App.vue file Below is the content of my App.vue file : <template> <div> <AppHeader></AppHeader> ...