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

Instead of only one menu icon, now there are three menu icons displayed on the screen. (Additionally, two more divs containing

When visiting on a smartphone browser, you may notice that instead of one menu icon, three icons appear. Upon inspecting the elements, you will find that there are three div's that look like this: <div class="responsive-menu-icon">&l ...

What is preventing me from displaying the results on the webpage?

Currently, I am utilizing Express alongside SQLite and SQLite3 modules. However, upon running the server, the data fails to display on the initial request. It is only after a page refresh that the data finally appears. I attempted a potential solution by ...

What steps do I need to take in order to generate a legitimate link annotation within Adobe Acrobat by utilizing Acrobat

Seeking guidance on how to embed an Acrobat Javascript within Adobe Acrobat in order to generate a link annotation. The current method involves using the "addLink" function within the document object, which triggers a Javascript action upon clicking the li ...

The component's $scope holds the $rootScope variable

Hey there! I've just been assigned the task of maintaining a client written in AngularJS, and I must admit I'm not very familiar with Angular. However, I stumbled upon this piece of code that seems quite unconventional... There's a service ...

Using React Native to create a concise text component that fits perfectly within a flexbox with a

Within a row, there are two views with flex: 1 containing text. <View style={{ flexDirection: "row", padding: 5 }}> <View style={{ flex: 1 }}> <Text>Just a reallyyyyyyyy longgggg text</Text> </View> ...

Tips for personalizing the tooltip on a line chart in Vue.js using Chart.js

Attempting to create a line graph using chart js and vue, but new to both technologies. In the chart below, I am trying to change the tooltip to display "10 Answers July 19, 2023". I have attempted to use the beforeLabel and afterLabel options without succ ...

The argument provided needs to be a function, but instead, an object instance was received, not the original argument as expected

I originally had the following code: const util = require('util'); const exec = util.promisify(require('child_process').exec); But then I tried to refactor it like this: import * as exec from 'child_process'; const execPromis ...

The size of objects on canvas is not consistent when loading with fabric.js loadFromJSON

Click here to view the code var canvas = new fabric.Canvas('canvas_1'); var canvas2 = new fabric.Canvas('canvas_2'); var imgObj = new Image(); imgObj.src = "https://gtaprinting.ca/wp-content/uploads/2021/05/blank-t-shirt-front-gre ...

Comparing the functions of useMemo and the combination of useEffect with useState

Is there a benefit in utilizing the useMemo hook instead of using a combination of useEffect and useState for a complex function call? Here are two custom hooks that seem to function similarly, with the only difference being that useMemo initially returns ...

React: automatically close other SubMenus when a new SubMenu is opened

Is there a way to automatically close all other open SubMenus when a user opens a new SubMenu? If anyone has a solution, I would greatly appreciate the help! This is my code: Menu.tsx -> const Menu: React.FC = ({ data }) => { return ( ...

Executing a task within a Grunt operation

I have integrated Grunt (a task-based command line build tool for JavaScript projects) into my project. One of the tasks I've created is a custom tag, and I am curious if it is feasible to execute a command within this tag. Specifically, I am working ...

Ways to retrieve response data from the server using angularjs

In my current setup, I have a Node.js server handling the authentication process while AngularJS is used on the frontend. When a user clicks a button to sign in with Facebook, the server takes care of all authentication aspects and redirects to the URI of ...

Addressing Equity Concerns within JavaScript Programming

I can't figure out why the final line in this code snippet is returning false. Is it not identical to the line above? const Statuses = Object.freeze({ UNKNOWN : 0, OK : 1, ERROR : 2, STOPPED : 3 }); class myStatus extends Object{ co ...

Seamless infinite background scrolling on the canvas without any disruptions

In my HTML5/JS project, I have implemented infinite background scrolling using multiple canvases. The challenge I am facing is that while the animation is smooth after rendering, there is a quick hiccup when transitioning to the next frame due to the need ...

Unable to locate phonepe.intentsdk.android.release:IntentSDK:2.4.1 while integrating React Native

android build gradle : // Configuration options for all sub-projects/modules are defined in the top-level build file. buildscript { ext { buildToolsVersion = "33.0.0" minSdkVersion = 21 compileSdkVersion = 33 targetSdkVersion = ...

jQuery: Issue with controller function execution when using ajax

Currently, I am working on developing a web application using C# MVC that dynamically fetches information from a server to enhance performance. However, I have encountered some errors and I am having trouble pinpointing the exact cause. Allow me to provid ...

Running a JavaScript function within a designated div element

I'm currently facing an issue with executing a javascript function - onload only in a specific div. I seem to be stuck on this problem, so if anyone could offer some assistance, I would greatly appreciate it. Thank you very much in advance! functio ...

Jest tutorial: mocking constructor in a sub third-party attribute

Our express application uses a third-party module called winston for logging purposes. const express = require('express'); const app = express(); const { createLogger, transports } = require('winston'); const port = process.env.PORT | ...

Using nodeJS's util module to format and pass an array

I've been using util.format to format strings like this: util.format('My name is %s %s', ['John', 'Smith']); However, the second parameter being an array ['John', 'Smith'] is causing issues because m ...

Exploring a promise-based angular service through testing

Currently, I am using browserify to bundle an angular service. In order to test this service, I have opted for jasmine and the service is defined as follows: angular .module('Client', []) .factory('client', ['url', ' ...