Is there a way to automatically assign an index to ng-show values in AngularJS?

Why is the function not working?

<div ng-repeat="report in reports track by $index">
    <div ng-model="myDiv{{ $index }}" ng-show="myDiv{{ $index }}">{{ report }} {{ index }}</div>
</div>

How to make it work correctly?

<div ng-repeat="report in reports track by $index">
    <div id="myDiv{{ $index }}"  name="myDiv{{ $index }}">{{ report }} {{ index }}</div>
</div>

While adding $index to names or ids works fine, it behaves differently for other directives. This creates a challenge when trying to implement dynamic behaviors.

The objective is to display and manage multiple reports with date range pickers in a sortable table format. Each report should have its own date picker for customization. Here is an example of the desired functionality...

<tr ng-repeat="report in reports track by $index">
    <td><p>{{ report.title }}</p></td>
    <td>
        <div id="dateRangePicker{{ $index }}">
            <div id="fromDateWrapper{{ $index }}" class="col-md-6">
                <p class="input-group">
                    <input id="fromDateInput{{ $index }}" type="text" ng-blur="validDate($event,$index)" is-open="openFrom{{ $index }}" ng-model="fromDate{{ $index }}" class="form-control calenderInput" datepicker-popup="MM/dd/yyyy" min-date="minDate" max-date="toDate" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close"/>
                    <span id="fromDateButton{{ $index }}" class="input-group-btn">
                        <button type="button" class="btn btn-default " ng-click="openCalender($event,'fromDate',$index)"><i class="glyphicon glyphicon-calendar"></i></button>
                    </span>
                </p>
            </div>      
            <div id="toDateWrapper{{ $index }}" class="col-md-6">
                <p class="input-group"> 
                   <input id="toDateInput{{ $index }}" type="text" ng-blur="validDate($event,$index)" is-open="openTo{{ $index }}" ng-model="toDate{{ $index }}" class="form-control calenderInput" datepicker-popup="MM/dd/yyyy" min-date="fromDate{{ $index }}" max-date="maxDate" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close"/>
                    <span id="toDateButton{{ $index }}" class="input-group-btn">
                        <button type="button" class="btn btn-default" ng-click="openCalender($event,'toDate',$index)"><i class="glyphicon glyphicon-calendar"></i></button>
                    </span>
                </p>
            </div>
        </div>
    </td>
   <td><button id="printReport{{ $index }}" type="button" ng-click="printReport($index)">Print Report</button></td>
</tr>

When $index is not included, it causes conflicts as all elements are linked to the same variables. Debugging this issue and finding a suitable solution is imperative for smooth functioning.

Hoping to resolve this matter promptly for seamless operation.

Answer №1

The task you are attempting to accomplish is not feasible, as you are incorrectly assigning `ng-model` to a `

` element when it should only be used with form elements like inputs. Additionally, utilizing `{{}}` brackets within a directive expression will not yield the desired result.

Have you considered storing your index pairs in an object and trying this approach instead:

$scope.myDiv = {};

<div ng-repeat="report in reports track by $index">
    <input type="text" ng-model="myDiv[index]" ng-show="myDiv[index]" />
</div>

Answer №2

Avoid depending on $index or id, instead rely on object. For example, in your scenario - report, I'm not sure what your report entails, but it should be something along the lines of:

<input type="text" ng-blur="validDate($event, report.fromDate)" ng-model="report.fromDate" class="form-control calenderInput" .../>

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

Creating a Dojo HTML template involves incorporating repetitive sections of HTML code within the template structure

I am working with a custom Dojo widget that is based on a template and has an HTML template stored in a separate .html file. Here is the Dojo Widget code snippet: define("dojow/SomeWidgetName",[ "dojo/_base/declare", "dijit/_WidgetBase", "dijit/_Templat ...

The onchange event does not seem to be functioning as expected in a dropdown menu that was dynamically added from a separate

Is there a way to display a list of tables from a database in a dropdown menu and allow users to select a table name? When a user selects a table name, I would like to show all the data associated with that table. The HTML file structure is as follows: & ...

The issue with the FileEntry.file() method arises when attempting to open an HTML file directly

I have been developing a drag-and-drop upload feature. In the drop event, I utilize e.dataTransfer.items to extract handles for all files and folders, then use the items[n].webkitGetAsEntry() method to obtain the FileEntry object. Lastly, I try to access t ...

Jest-Native encountered an error: "SyntaxError: Unable to use import statement outside of a module"

Trying to perform unit testing using https://github.com/callstack/react-native-testing-library along with https://github.com/testing-library/jest-native. I am able to test plain JavaScript files without any issues, but I am facing an error when testing com ...

Unable to communicate between react components

I am currently working on a project using React JS (jsfiddle). The issue I am facing is that the textbox does not update with the true/false value of the checkbox when it is checked. Can anyone provide insight into why this might be happening? var Custo ...

Is it possible to utilize both jQuery and AngularJS in our web application?

Is it feasible to incorporate both jQuery and AngularJS in our web application? Some sources suggest avoiding using them together due to their distinct lifecycles. We need to develop a responsive web application using ASP.NET WebApi and AngularJS. To achi ...

Is it conceivable to generate fresh errors from an Ajax success event?

Whenever a server side error occurs in PHP, it is captured as a hash and then transmitted back to the client side using AJAX in the form of JSON. This way, the errors are effectively passed to the AJAX success event. ... catch ($e) { echo ( array("err ...

Is it possible for me to route a URL to a particular content generated by Ajax on a separate webpage?

I appreciate anyone taking the time to help with this, especially since I already had to get 12 stitches. Here's what I'm dealing with: mysite.com/documentation - page with a menu and content section (content will load dynamically via Ajax w ...

Angular routes are failing to update the view even after attempting to refresh

I am facing an issue while trying to develop an angular app where the child state is not loading properly. app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('home& ...

Tips on how to customize an Ajax modal appearance

I need to customize the CSS styling of a modal for editing purposes. Can anyone provide guidance on how to set the width, height, and other properties using the code snippet below? // Open modal in AJAX callback $("modal").dialog({ modal: true, minH ...

An error will occur if you try to use $.ajax inside a function

I am facing an issue with a function that utilizes jquery's ajax to check an API for the success status of a variable. The goal is to return true if the "success" variable is true and false if it is false. Below is the code snippet: function checkLo ...

The v-autocomplete feature in vuetify doesn't allow for editing the text input after an option has been selected

Link to code on CodePen: CodePen Link When you visit the provided page and enter "joe" into the search box, choose one of the two Joes that appear. Try to then select text in the search box or use backspace to delete only the last character. You will no ...

Text field suddenly loses focus upon entering a single character

In my current code, I have functions that determine whether to display a TextField or a Select component based on a JSON value being Text or Select. However, I am facing an issue where I can only enter one letter into the TextField before losing focus. Sub ...

Resolving AngularJS routes while invoking a controller with ng-include

Feel free to check out my Plunkr demonstration by clicking here. In my application's app.js file, I've defined two controllers along with a route provider that includes a resolve function for the TestController. var app = angular.module(' ...

Issue: The object is unable to be executed as a function, resulting in the failure to return an array

Currently, I am extracting table values from the UI row by row. This involves clicking on each row and retrieving the corresponding data. exports.getTableData = function(callback){     var uiArray =[];     var count;         aLib.loadCheck(c ...

I'm curious whether there exists a polyfill available for the window.DOMParser() method that can

Seeking to modify the XML to JSON converter using DOMParser. Wondering if there is a method to adapt it for NodeJS. ...

Repetitive firing of events implemented using AngularJS

Hello, I'm currently trying to trigger an event repeatedly in AngularJS. Below is the code snippet: Here is the HTML code: <li ng-repeat="y in names | limitTo: 6" repeat-done="ratingwithng()"> <a href="<?php echo $this->config-> ...

Check for weaknesses in your project using NPM audit

While trying to install the npm package to retrieve the node module file, I encountered a total of 184 vulnerabilities (153 low, 1 moderate, 30 high) after running npm install. I am considering running npm audit fix to address these vulnerabilities, but ...

Encountering a Next.js application error while utilizing the button tag in conjunction with generating metadata

I keep encountering an issue with generateMetaData when trying to utilize the button tag. Can you help me resolve this problem? Currently, I am working with nextjs and I am unable to properly use the <button> tag. Whenever I implement generateMetaD ...

javascript image click activates checkbox with PHP support

Is it possible to add a feature that allows clicking on the displayed image to check the checkbox above? I'm having trouble with lines 29-32. Although I found an example, it didn't work for me. Thanks <html> <head> <title&g ...