Toggle the visibility of a button embedded within an ng-repeat loop

I am attempting to display or hide buttons within an ng-repeat loop, specifically in a simple table. I want to replace a delete button with a confirm button.

Below is my code:

..... Angular stuff .....

function ContactsCtrl($scope, $http) {
    $scope.order = '-id';
    $scope.currentPage = 0;
    $scope.pageSize = 15;
    $http.get('/events/<%= @event.id -%>/contacts.json').success(function(data) {
        $scope.contacts = data;
        $scope.numberOfPages=function(){
            return Math.ceil($scope.contacts.length/$scope.pageSize);
        }
    });

    $scope.clickDelete = function(e,t) {
        console.log("delete");
            // rest api stuff...
        $scope.contacts.splice(e, 1); // This WORKS!
    };
    $scope.showDelete = function(e,t) {
        e.showDeleteButton = true; // This DOES NOT
    };
}

In the HTML:

 <tr ng-repeat="contact in contacts | filter:search | orderBy:order |      startFrom:currentPage*pageSize | limitTo:pageSize">
<td><a href="/contacts/{{contact.id}}/edit">{{contact.email}}</a></td>

                        ...
<td><a href="#" ng-click="showDelete(contact)" class="btn btn-small">delete</a>
<a href="/contacts/{{contact.id}}" ng-show="showDeleteButton" ng-click="clickDelete(contact)" class="btn btn-small btn-danger">confirm</a>
    </td>
</tr>

Answer №1

It seems like the showDelete function is missing a return value. Additionally, there is a 'showDeleteButton' property in the JSON object that could be directly bound to.

Check out this example on Plunker: http://plnkr.co/edit/dq9we76TghSFlNc4qJU2

Answer №2

It appears that your intention is to make the delete button trigger a flag that will display the confirm button for actual deletion, am I right? ng-repeat generates a new child scope for each element, allowing you to simply set a 'confirmable' flag on the child scope and utilize it (fiddle):

<a ng-click="confirmable = true">delete</a>
<a ng-show="confirmable" ng-click="clickDelete(contact)">confirm</a>
<a ng-show="confirmable" ng-click="confirmable = false">cancel</a>

Furthermore, it seems like you are passing the contact object to the clickDelete function and using it as an index in the array which may not be correct. The fiddle makes use of indexOf to determine the index for deletion.

Answer №3

Here is my method:

Using JavaScript:

$scope.removeContact = function(contact, index) {/* ... */ $scope.contacts.splice(index, 1);};
$scope.showConfirmDelete = function(contact) {contact.confirmation = true;};
$scope.cancelDelete = function(contact) {contact.confirmation = false;}
$scope.toggleConfirmation = function(contact) {return contact.confirmation;};

In the HTML:

<a href="#" ng-click="showConfirmDelete(contact)" ng-hide="toggleConfirmation(contact)" class="btn btn-small">delete</a>
<a href="/contacts/{{contact.id}}" ng-click="removeContact(contact,$index)" class="btn btn-small btn-danger" ng-show="toggleConfirmation(contact)">ok</a>
<a href="#" ng-show="toggleConfirmation(contact)" ng-click="cancelDelete(contact)" class="btn btn-small">cancel</a>

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

Tips for adjusting the placeholder color in Material UI using React JS

Is there a way to customize the background color and flashing color of the Skeleton component in Material UI? I would like to implement custom styling for it, similar to what is shown below: <Skeleton variant="circle" classes={{root:'pla ...

Ways to Deduct 10 Days from a Date using JavaScript

After receiving some helpful suggestions, I managed to solve my date issue by using moment.js. Here is the snippet of code where I implemented moment.js: var preorderdate = moment(date).subtract('days',10).format('MMMM D, YYYY'); var r ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...

NodeJS - The server returns a 404 error before ultimately displaying the requested page

I'm having trouble with my nodeJS application. When I make an asynchronous call using ajax, the server first responds with a 404 error before loading the page. The application functions properly, but I keep receiving repetitive logs stating "Can' ...

When a new component is loaded, React Martial UI component may face issues due to overwriting or

Currently, we are working on a vast web application that utilizes jquery and bootstrap. Our current task involves transitioning this extensive app to React with Material UI, piece by piece. As we progress towards transforming it into a React app, everythin ...

The functionality to show/hide based on the selected value upon loading is malfunctioning

When a user selects a widget type from a dropdown on my form, different form fields are displayed based on the selection. However, upon initial load of the form (which is loaded via an ajax call), these fields remain hidden. Below is the code snippet that ...

Looking for a way to automatically update your JavaScript code on your Minecraft (Bukkit)

One of my clients has requested a website design that includes a player display for each server, updating every five seconds. I'm not sure where to start with this task. Below is an example for reference. Any guidance on how to achieve this would be g ...

Exploring the Efficiency Enhancements in the next/image Optimization Process within Next.js

I've been delving into Next.js and using the next/image component for image rendering. While leveraging it to enhance image loading in my project, I've become intrigued by the intricate workings behind the scenes. I'm particularly interested ...

Dragging and Dropping Electron Files into an Inactive Window

I am exploring the implementation of drag and drop functionality within an electron window, utilizing the suggested approach of sandboxing processes. This involves isolating ipcMain from ipcRenderer and creating a bridge through a preload.js script (refer ...

Save the JWT token securely within a closure

Someone mentioned that the recommended way to store JWT tokens is as follows: access_token in the application memory (like closures) refresh_token in cookie entries (HttpOnly) Currently, my access_token is stored in localStorage and used for checking aut ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

Aligning validation schema with file type for synchronization

Below is the code snippet in question: type FormValues = { files: File[]; notify: string[]; }; const validationSchema = yup.object({ files: yup .array<File[]>() .of( yup .mixed<File>() .required() .t ...

Images are failing to show up in the iPhone design

Encountering issues with displaying images on an iPhone? You can replicate the problem by minimizing your browser window horizontally. Here is a link showcasing the problem: here. To temporarily fix this, try zooming out the browser (Ctrl+-). You can see a ...

Enable retrieval of calculated time duration in jQuery time picker

After implementing two separate timepickers for calculating a time duration, I am looking to access this computed duration for further calculations later on the page. How can I retrieve the duration that is already displayed to the user after using the sec ...

The page refreshes when the anchor element is clicked

Currently, I am working on enhancing a web application that is built on the foundation of traditional aspx (asp.net) web forms with elements of Angular 6 incorporated into it. My current assignment involves resolving a bug that triggers a page refresh whe ...

The AngularJS element fails to display on the screen

I am currently learning AngularJS and I am struggling to understand how components are linked to the view in the tutorial. I have created a component that is quite similar: angular.module('phonecatApp').component('nameList', { temp ...

Refresh the data using the Ajax function

I am attempting to implement a delete function using Ajax. function delCatItem(catitem){ var theitem = catitem; $.ajax({ url: "movie/deleteitem/", type: "POST", data: { "movieid" : catitem ...

Using JavaScript to make API calls with JSON and AJAX

Find type: Procedure : POST Link: http: // beta.etruckingsoft.com:8800/contact/searchContacts INFORMATION: {"Company Id" : 2, "SearchVal" : "b", "Contact Type":"Broker", "token" : "eyJhbGciOiJIUzI1NiJ9.MTkzMA.g132LGIzcwJaJRGa31q-k1hk6u79H0wIj1xjCJzLpZ ...

Guide on extracting data from an HTML table column and saving it to a JavaScript array with the help of JQuery

Suppose there is a table column containing 10 rows, each with <td id="num"> and some text value. Is there a way to utilize JQuery in order to iterate through every row within the column and store the values in a JavaScript array? I attempted the co ...

Issues with loading cascading drop down list data from database using MVC, JSON, and C#

Hello everyone, I'm fairly new to MVC/Javascript and have been experimenting with different tutorials in order to create a cascading drop down list for selecting State and City on an MVC view. In my latest attempt, I followed this example. While the ...