Using AngularJS, deleting items by their $index with ng-repeat

I'm currently working with two directives: a query builder and a query row. The query builder directive utilizes ng repeat to display query rows from an array. While the add button functions properly, I am looking to add a delete button as well. However, I have encountered an issue where I can't seem to access $index in order to pass it as an argument to the delete function (i.e., delete($index)).

Below is the JS code:

.directive('queryBuilder', function() {
  return {
    restrict: 'E',
    scope: {},
    controller: function($scope) {
      $scope.rows = [{}]

      //add method not utilized - delete in future
      $scope.add = function() {
        $scope.rows.push({})
      }

      $scope.$on('addRowRqst', function(evt) {
        console.log('add rqst received')
        $scope.rows.push({})
      });
      $scope.$on('deleteRowRqst', function(evt) {
        console.log('delete rqst received')
        $scope.rows.push({})
      });        
    },
    templateUrl: 'queryBuilderTemplate.html',
  }
}).directive('queryRow', function() {
  return {
    scope: {},
    restrict: 'EA',
    templateUrl: 'queryRowTemplate.html',
    controller: function($scope) {
      $scope.addRqst = function() {
        console.log('addRowRqst click')
        $scope.$emit('addRowRqst')
      };
      $scope.deleteRqst = function(index) {
        console.log('deleteRowRqst click')
        $scope.$emit('deleteRowRqst')
      };
    },
    link: function(scope, elem, attrs) {

    }
  }

And here is the HTML code of the query builder template:

<form role="form">
  <query-row ng-repeat="row in rows track by $index"></query-row> 
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Lastly, this is the Delete button within the query row template. When attempting to pass $index as an argument, it appears as 'undefined':

<button class="btn btn-default" ng-click="deleteRqst($index)" type="submit">Delete Row</button>

If you'd like to see the full example, check out the Plunker link provided below:

http://plnkr.co/edit/rDkXpIgiOSoNvLNPsVbP

My main goal is to implement a functioning Delete button that can remove the selected row.

Answer №1

The reason for this issue is due to $index being located in the parent scope while an isolate scope is utilized in your query-row directive.

To address this problem, consider implementing the following:

<button class="btn btn-default" ng-click="deleteRqst($parent.$index)" type="submit">Delete Row</button>

Alternatively, you can eliminate the use of an isolate scope altogether.

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

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

Unexpected next() error occurred

Currently, I am working on a project using node.js along with express and MongoDB. I have encountered an error that I cannot seem to understand. When I remove the next() function call, everything works perfectly fine. However, when I include next(), it tr ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...

Discovering the power of Next.js Dynamic Import for handling multiple exportsI hope this

When it comes to dynamic imports, Next.js suggests using the following syntax: const DynamicComponent = dynamic(() => import('../components/hello')) However, I prefer to import all exports from a file like this: import * as SectionComponents ...

Ensuring secure communication with PHP web service functions using Ajax jQuery, implementing authentication measures

jQuery.ajax({ type: "POST", url: 'your_custom_address.php', dataType: 'json', data: {functionname: 'subtract', arguments: [3, 2]}, success: function (obj, textstatus) { if( !('error' in obj) ) { ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

Angular4 and jQuery working together for effective navigation and pagination

Trying to implement pagination in angular 4 and jQuery, but encountering an issue where clicking on the next button causes it to skip through multiple pages at once (2, then 3, then 5)... Component code: addClass(x) { $(".page-item").click(function () ...

ASP.NET MVC - AjaxContext is a powerful feature provided by the

I recently attempted to delve into the AjaxContext utilized by ASP.NET-MVC in scenarios such as Ajax Actionlinks and their clientside functions like onSuccess and onComplete. However, I must admit that I found it quite confusing... Is there any documentati ...

Individual Ajax data

Starting out with javascript, I'm a bit unsure of how to tackle this task. Essentially, I am looking to implement a for loop within the ajax data call, rather than listing each item manually. jQuery(document).ready(function() { ...

Utilizing Angular to integrate with an external API

I have encountered an issue while trying to connect to the Expedia API. In order to do so, I need an API key and ID. Initially, I utilized JSONP for this connection but ran into a bug causing problems. Additionally, storing my API key in JavaScript poses ...

Utilizing lazy evaluation, multiple functions are triggered by ng-click in succession

Successfully disabled ngClick on an element when the scope variable (notInProgress) is set to true as shown below: <a data-ng-click="notInProgress || $ctrl.setTab('renewal');</a> Now, I want to include additional functions to be execut ...

Node - ensure that each API call finishes before initiating the next one

Currently, I am encountering an issue with my POST request within the 'add-users' route. I have initialized an array named success and aim to trigger the next API call once a response is received. It seems that the problem lies in sending too ma ...

Spacing issues with inline-block elements when dealing with a large quantity of items

Currently, I am tackling the JS/jQuery Project for The Odin Project and I am confident that my solution is working exceptionally well. However, the issue I am facing is that when dealing with larger amounts of elements (around 40-45 in JSFiddle and 50-52 ...

Label positioning for checkboxes

Is there a way to display the checkbox label before the actual checkbox without using the "for" attribute in the label tag? I need to maintain the specific combination of the checkbox and label elements and cannot use nested labels or place other HTML elem ...

What is the best way to verify values in Vuejs based on their length?

<button type="submit" :disabled="(user.password && !$v.user.password.valid) || (user.confirmPassword && !$v.user.confirmPassword.sameAsPassword)">sda </button> By implementing a method based on character len ...

Guide on creating an HTML5 rectangle for reuse using the Prototypal Pattern

I'm struggling to grasp Prototypal Inheritance through the use of the Prototypal pattern by creating a rectangle object and an instance of that rectangle. It seems like it should be straightforward, but I'm having trouble understanding why the Re ...

Utilizing the request module in Node.js with ExpressJS

Currently, I am in the process of creating a helper method within my code that will handle user authorization. This function, named "usePermissions", is being developed following the React approach but for backend functionality. Upon implementa ...

Looking for assistance with using an array in a for loop with an if-

I'm having trouble with a For loop array. I need to retrieve the data that is opposite of a given function, but when I use arr[i] != elem, it prints out the entire array. On the other hand, if I use arr[i] == elem, it gives me the array that I don&apo ...

Help with iterating over an array containing unique URLs, and set the `window.location.href` to each URL as we loop through the array

Do you have a question that needs answering? It may seem simple at first glance, but I've been struggling to find a solution. My goal is to create a PHP loop where the "$ad_id" varies each time the loop is executed. Then, I want to display a button ea ...

Initiate magnific popup only when the body class meets certain criteria

I am currently utilizing a plugin called magnific popup and I have a requirement to display a video when a user navigates to the site (while also ensuring it doesn't show every time). To achieve this, I am using localStorage. The code for this functio ...