Numbering the items in ng-repeat directive

I am facing a challenge with my AngularJS directive that is recursively nested within itself multiple times. The issue lies in the fact that the names of items in ng-repeat conflict with those in the outer element, causing it to malfunction. To illustrate the problem, consider the following simple code snippet:

<div ng-repeat="item in items">
    <div ng-repeat="item in items">
    {{item.value}}
    </div>
</div>

In this scenario, the value of the item will match that of the outer <div> instead of the inner one.

My goal is to assign a distinct number based on the nesting level (e.g., 0 for root ng-repeat, 0-1 for the second child of the root directive, 1-0 for the first child of the second directive, and so forth) to each item name when generating a template using the directive. This would result in a structure like this:

<div ng-repeat="item-0 in items">
    <div ng-repeat="item-0-0 in items">
    {{item.value}}
    </div>
</div>

Below is the snippet of the directive I have been working on:

app.directive('recursiveFields', function ($compile, $http) {
    return {
        scope: {
            field: '=field',
            model: '=model'
        },
        restrict: 'E',
        replace: true,
        controller: "httpPostController",
        template: '<div ng-repeat="nestedField in field.nestedFields"><div ng-show="{{!nestedField.isEntity && !nestedField.isEnum}}">' + '<p ng-show={{nestedField.isRequired}}>{{nestedField.name}}*: </p>' + '<p ng-show={{!nestedField.isRequired}}>{{nestedField.name}}: </p>' + '<input type="text" ng-model="model[field.name][nestedField.name]" ng-change="getCreateEntityAsText()"' + 'class="form-control" placeholder="{{parseClassName(nestedField.type)}}">' + '</div>' + '<div ng-show="{{nestedField.isEnum}}">' + '<p ng-show={{nestedField.isRequired}}>{{nestedField.name}}*: </p>' + '<p ng-show={{!nestedField.isRequired}}>{{nestedField.name}}: </p>' + '<select ng-model="model[field.name][nestedField.name]" ng-change="getCreateEntityAsText()" class="form-control">' + '<option></option>' + '<option ng-repeat="enumValue in nestedField.enumValues" label={{enumValue.name}}>{{enumValue.ordinal}}</option>' + '</select>' + '</div>' +

        '<div ng-show="{{nestedField.restResourceName != null}}">' + '<accordion close-others="oneAtATime">' + '<accordion-group heading={{nestedField.name}} is-open="false">' + '<button type="button" ng-click="appendDirective($event, model, field)">I should append a "recursiveFields" directive</button>' + '</accordion-group>' + '</accordion>' + '</div>' + '</div>',

        link: function (scope, element, attrs, controller) {
            if (scope.field && scope.field.restResourceName != null) {
                $http.get(CONSTANTS.EXPLAIN_URL + "/" + scope.field.restResourceName)
                .success(function (data, status) {
                    scope.field.nestedFields = [];
                    data.content.resource.fields.forEach(function (field) {
                        if (field.isEnum) {
                            $http.get(CONSTANTS.ENUMS_URL + scope.$root.parseClassName(field.type)).success(function (data, status) {
                                field.enumValues = [];
                                for (var index in data.content.values) {
                                    field.enumValues.push(data.content.values[index]);
                                }
                            })
                        }
                        scope.field.nestedFields.push(field);
                    })
                })
            }

            scope.appendDirective = function ($event, model, field) {
                //              var recursiveFields = $('<recursive-fields model="model" field="field"></recursive-fields>');
                var recursiveFields = $('<p>new text </p>');
                recursiveFields.insertAfter($event.target);
                $compile(recursiveFields)(scope);
            }

            scope.getRandomSpan = function () {
                return Math.floor((Math.random() * 6) + 1);
            }
        }
    }
})

If you have any suggestions or solutions on how to address this issue, please feel free to share. Your input is greatly appreciated.

Thank you.

Answer №1

Have you considered using a different variable name?

<div ng-repeat="item in items">
    <div ng-repeat="innerItem in items">
        {{item.value}} 
        {{innerItem.Value}}
    </div>
</div>

Alternatively, your directive could utilize the following template:

template: '<div ng-repeat="nestedField[$id] in field.nestedFields .....">

In this case, $id would be the identifier of the new scope created by your directive.

Remember to specify $id when accessing scope variables:

<div ng-show="{{nestedField[$id].restResourceName != null}} ...>

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

Utilize a personalized useFetch hook in React.js to transmit a POST request and obtain a response

I recently came across a great resource on this website that provided the logic for a useFetch hook. My goal is simple - I want to send a post request and then map the response into a specific type. While this seems like it should be straightforward, I&apo ...

An issue has arisen in the production environment on AWS EC2 due to a problem with Nodemailer

When using nodemailer with node.js to send emails, I have set up the following configuration: var transporter = nodemailer.createTransport({ service: 'gmail', host: 'smtp.gmail.com', auth: { ...

What is the purpose of using an open quote and bracket in the `eval('('+jsonString+')')` syntax for parsing a JSON string?

What is the rationale behind this particular syntax structure? eval('(' + jsonString+ ')') When it comes to parsing JSON text, Crockford explains that "The text must be wrapped in parentheses to prevent any confusion with JavaScript& ...

The persistent state is not being saved correctly by Redux-Persist and is instead returning the initial

I have included redux-persist in my project, but for some reason it is not persisting the state as expected. Instead, I keep receiving the initial state whenever I reload the page. Below is the snippet of my root-reducer: import { combineReducers } from & ...

What is the best way to incorporate Electron browser windows within Angular-CLI components?

How can I use electron browser window inside components in angular-cli if it doesn't accept it? I encountered an error with fs.existsync. Are there any alternative options to integrate electron with angular2 components? var electron = require(&apos ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...

The method to eliminate the default active class using AngularJS when clicking on different links

Here is the scenario: The first link is initially active and highlighted with the active class when the page loads. <a class="button active" ng-click="$parent.Filter = ''" ng-class="{ 'active': Filter === '' }"> Test l ...

Changing the $scope of the parent in Angular

Currently, I am facing the following scenario: When selecting a city from a menu in view+Ctrl 1, I need to $watch the city attribute and refresh the jobs in that city from the API. Then, I must modify $scope.model.myJobs accordingly. In the main view ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

What are the potential drawbacks of dynamically generating a form within an Angular controller?

Currently, I am handling this task within a controller: $scope.logout = function() { var logout_form = document.createElement("form"); logout_form.setAttribute("method","post"); logout_form.setAttribute("action","logout"); document.body. ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

Dimensions of HTML Container on Google Website

I'm attempting to incorporate a collapsible table using HTML Box in a Google site. The code for the collapsible table can be found at http://tutorials.seowebpower.com/google-sites-advanced/collapsible-table. Here is the code: <html> <head> ...

Adjusting the slide display in angular-slick based on the window's width automatically

I am new to working with Angular and I'm trying to create a responsive slideshow using angular-slick. Here is an example of my code: <slick infinite="true" slides-to-show="4" slides-to-scroll="1" prev-arrow=".slick-prev" next-arrow=".slick-next"&g ...

Utilizing AJAX and javascript for extracting information from websites through screen scraping

Is it possible to scrape a screen using AJAX and JavaScript? I'm interested in scraping the following link: I tried the technique mentioned on w3schools.com, but encountered an "access denied" message. Can anyone help me understand why this error is ...

Implementing adaptive window.scrollY listener in React to account for different screen sizes

I am currently using a useEffect hook to create a fade-in effect for text based on scroll position. While this works perfectly on my 27-inch MAC screen, I am facing challenges when viewing it on a smaller screen. I am unsure how to adjust the useEffect to ...

The functionality of Angular JS Material's mdMedia appears to be malfunctioning

Yes, I have a toolbar on my website. <md-toolbar layout="row"> <div class="md-toolbar-tools"> <md-button ng-click="mainCtrl.toggleSidenav('left')" ng-hide="$mdMedia('min-width: 16cm')" class="md-icon-b ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

Web page containing information from IPv6 and IPv4 sources exclusively

Is it possible to have an HTML5 page accessible through both IPv4 and IPv6, while only allowing CSS style and JavaScript from other domains via IPv4? Unfortunately, it seems that this setup does not function properly for pure IPv6 connections. Will th ...

Filtering data in Angular with custom specifications

I'm currently attempting to filter data from a factory using boolean controls. I seem to be encountering difficulties, possibly due to syntax errors and my lack of complete understanding of Angular. I've been stuck at this point for quite some ti ...

The error message "Unable to iterate over undefined property in Node.js using EJS and JavaScript" popped up

I've been struggling with the error "Cannot read property 'forEach of undefined" for two days now and I just can't seem to figure out the problem. Any help would be greatly appreciated. Here is the code: bruidstaart.js page where I am tryin ...