Uncovering the Solution: Digging into a Nested ng-repeat to Access an Array in AngularJS

I am working with a recursive array in JavaScript:

[{
  type: 'cond',
  conditionId: 1,
  conditions: undefined
},
{
  type: 'cond',
  conditionId: 2,
  conditions: undefined
},
{
  type: 'group',
  conditionId: undefined,
  conditions: [{
      type: 'cond',
      conditionId: 3,
      conditions: undefined
    },
    {
      type: 'cond',
      conditionId: 4,
      conditions: undefined
    }]
}]

In my AngularJS application, I am using ng-repeat to display this recursively with an inline template:

<script type="text/ng-template" id="recursive_template.html">
<div> some logic </div>
        <div ng-repeat="cond in cond.conditions" ng-include="'recursive_template.html'"></div>
  <div> some more logic  </div>
</script>

<div ng-controller="EditRulesController">
  <div ng-repeat="cond in conditions" ng-include="'recursive_template.html'" class="row">
  </div>
</div>

Everything is functioning properly. However, I now want to remove an item from the inner ng-repeat. I have the index of the clicked item (to delete) and access to the object cond as a parameter on ng-click. I can also use $parent, but it refers to the root object...

Is there a way to access the inner array without having to manually search through the entire conditions array recursively? It seems odd that the index of the inner array is easily accessible, but not the actual array instance.

Any advice on how to tackle this issue would be greatly appreciated. Thank you.

EDIT 21/03/2016

Prior to the accepted answer, a 'brute-force' approach was implemented like so:

        $scope.deleteConditionClick = function (id) {
            deleteCondition($scope.conditions, id);
        };

        function deleteCondition(conditions, id) {

            var conds = conditions;
            if (conds) {
                for (var i = 0; i < conds.length; i++) {
                    if (conds[i].type === 'cond') {
                        if (conds[i].conditionId === id) {
                            conds.splice(i, 1);
                            return true;
                        }
                    } else if (conds[i].type === 'group') {

                        deleteCondition(conds[i].conditions, id);
                    }
                }
            }
        }

I hope this helps others facing a similar challenge.

Answer №1

Consider implementing the delete functionality with ng-click="cond=undefined". This simple action will clear the deleted condition, allowing you to manage visibility in the view using ng-show/ng-if.

Answer №2

Here is my technique for retrieving items with multiple indexes:

<div ng-repeat="x in outerArray" ng-init="outerIndex = $index">
  <div ng-repeat="y in innerArray">
    {{ innerArray[outerIndex] }}
  </div>
</div>

I believe this is the solution you were looking for. I hope this explanation helps.

Answer №3

To make things easier, you can pass both the parent array and the object as parameters, such as

ng-click="removeItem(items, item)"
, then utilize the .findIndex() method to locate the index of the specified object. For example, your function could look like this:
$scope.removeItem = function(items, item) {index = items.findIndex(i => i === item)...}

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

Create a new object by extracting JSON data using JavaScript

I am attempting to extract various data elements from a JSON file and place them into an object. My ultimate goal is to then convert this object back to JSON format, containing only the desired data. I believe that structuring the object like this might w ...

Click event recursion occurs due to the use of $.post

I have a collection of product rows available for customers to select from. Each row is designated with the class "product-line". Upon clicking on a row, I aim to visually indicate its selection status by toggling the "product-checked" class, and subsequen ...

The API request is experiencing delays due to the large dataset of 250,000 records

Utilizing API calls to retrieve data for the frontend is essential, but with a database table containing 250,000 rows, efficiency becomes a concern. In my .NET Core application, I implement the following query: IQueryable<Message> query = context.Me ...

How can AngularJS handle uploading multipart form data along with a file?

Although I am new to angular.js, I have a solid understanding of the fundamentals. My goal is to upload both a file and some form data as multipart form data. I've learned that this is not a built-in feature of angular, but third-party libraries can ...

When using an `if` statement in CSS to determine if the value of `left` is

Is there a way to trigger an event only when the object reaches a specific percentage of its left position? I am trying to achieve this using jQuery with the .css() method. Here is what I have so far: HTML: <div id="midDiv"><img ..../></di ...

Using Node.js to send a photo through a Telegram Bot

I've been trying to send a photo via node.js using this function, but it's not working. telegram-bot-api https://www.npmjs.com/package/telegram-bot-api var telegram = require('telegram-bot-api'); var api = new telegram({ token: & ...

Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no oth ...

What is the best way to retrieve a specific value in an array object using JavaScript?

I'm working with an array that has the structure shown below: balance = [ {id: 2, is_selected: true}, {id: 4, is_selected: true}, {id: 15, is_selected: false}, {id: 137, is_selected: false}, {id: 30, is_selected: false} ]; Is ther ...

Are there alternative methods for inserting data into an array in JavaScript?

I'm having trouble with my code that is supposed to push data to an array variable, but instead I'm getting a blank array. Can someone help me figure out what I'm doing wrong? let users = [] // Here is where I'm looping through an aja ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

Navigating through a JSON object in JavaScript by employing regular expressions

Is there a way to extract the "Value" of elements "Data1", "Data2", "Data3", "Data4" from a JSON object without resorting to regex? I've heard that using regex with JSON is not recommended. <script> abc = { "model": { ... } } </script> ...

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 ...

What causes certain files to sporadically duplicate themselves in Visual Studio Code?

While using vscode for NodeJS development, I have noticed that certain files seem to duplicate themselves sporadically. Why is this happening and what steps can I take to resolve it? I am unsure of how to tackle this issue... ...

What is the best way to showcase a photo selected using an HTML input within a div container?

My goal is to select a photo from a folder and display it on a webpage, but I have struggled to find a working solution. Can this be achieved using just basic HTML, CSS, and JS? I am new to web development, so please forgive me for any beginner questions. ...

Cross domain widget ajax request

Our company offers a widget for clients to add to their websites. This widget requires a call to our website to validate user-entered data. However, due to domain restrictions, making ajax calls from the client's website to ours is not permitted. Is ...

Steps to retrieve the search box input value and submit it in an AngularJs component using the Enter key

I'm facing an issue where I am trying to fetch the search list using speciesName from a table. However, when I attempt to retrieve the data by pressing the enter key, it is returning an error stating that the input data is undefined. Is there a way ...

Is memory allocated for 32 bits for variables with an undefined value in Javascript?

If I have a function with the signature below: function test(variable1, variable2) {} And I call it with only one parameter: test(5); Then within the test function, variable2 will be created but with a value of undefined. I'm interested to know if ...

Identify the fields in the form that have been edited for easier reference

Seeking guidance on creating a form with interactive input box fields. When a user inputs something, the field highlights in orange. Moving to another field removes the highlight and focuses the new box. Clicking "save" stores the form data. Pressing "mo ...

Tips for converting a raw SQL query to Knex syntax

Recently delving into the world of development, I've come across knex for the first time. Issue: I have a raw SQL query that is functioning correctly. Now, I'm attempting to utilize knex for this query. To better understand how things operate, I ...

Tips for obtaining the identifier of a div element while employing the bind() function in jQuery

Imagine having the following div. <div id="456" class="xyz">Lorem Ipsum</div> If I want to execute a function when this specific div is hovered over, I can achieve it like this: $(".xyz").bind({ mouseenter : AnotherFunction(id) }); Prio ...