Navigating through the Table using AngularJS

I was able to successfully loop through a table using AngularJS to retrieve values from a specified scope named {{rec}} as shown below.

HTML

             <div id="AngularContainer" data-ng-app="myApp" data-ng-controller="myCtrl">
             <a data-ng-click='<%# "ShowFiles("+ Eval("FilesNames") + ")" %>' style="cursor: pointer">
                <table id="fils" style="display:none;">
                    <thead>
                        <tr>
                            <td>File Name</td>
                            <td>Designation</td>
                        </tr>
                    </thead>
                    <tr data-ng-repeat="rec in records">
                        <td style="border: 1px solid #000000">{{rec}}</td>
               // The values here are displayed successfully when button #Second is pressed, because there is a scope named {{rec}}
                        <td style="border: 1px solid #000000">
                        <input data-ng-model="naming" type="text" style="width: 200px" />
               // However, the values do not display when I press button #Second, because (data-ng-model="naming") that scope is not related to {{rec}}
                        </td>
                    </tr>
                    <tfoot>
                        <tr>
                            <td colspan="2" style="text-align: center">
                                <input id="Second" data-ng-click="dothat()" class="sav" type="button" value="Save" />            
                            </td>
                        </tr>
                    </tfoot>
                </table>
            <div id="fnalmsg"></div>
          </div>

Angularjs

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function ($scope) {
        $scope.ShowFiles = function (elm) {
            $scope.records = elm;
        };

        $scope.dothat = function () {
            var msg = document.getElementById("fnalmsg");

            var index = 0;
            $scope.records.forEach(function (rec, naming) {
                msg.innerHTML =
                msg.innerHTML + 'row #' + (index++) + ': ' + JSON.stringify(rec) + ' --- ' + naming + '<br />';
            });
        };
    });
  </script>

However, I encountered an issue with looping through an undefined scope named (data-ng-model="naming") which is meant to store values.

The final output appeared as follows:

row #0: "WIN_20170226_191746.JPG" --- 0
row #1: "WIN_20170226_191848.JPG" --- 1
row #2: "WIN_20170226_191908.JPG" --- 2

The expected output should be like this:

row #0: "WIN_20170226_191746.JPG" --- "Friends"
row #1: "WIN_20170226_191848.JPG" --- "Animals"
row #2: "WIN_20170226_191908.JPG" --- "Cars"

In simpler terms: How can I make (data-ng-model="naming") display names like "Friends","Animals","Cars" as entered in the ng-model="naming" inputs rather than showing unwanted values like 0,1,2 ?

Answer №1

If you find yourself in need of a separate "naming" variable for each iteration within the ng-repeat loop, you can define a data-ng-model="rec.naming" so that each item in the records list will have its own bound naming property. In your controller file, you can update your function as follows:

 $scope.records.forEach(function (rec) {
            msg.innerHTML =
            msg.innerHTML + 'row #' + (index++) + ': ' + JSON.stringify(??) + ' --- ' + rec.naming+ '<br />';
        });

Alternatively,

You could utilize data-ng-model="naming[$index]" to bind to a new list. In the JS file, you can access naming[index].

In my opinion, the latter approach appears to be the better solution. However, in certain scenarios, the first method may be more suitable. Consider using the second approach based on your specific requirements. Feel free to share your thoughts on these approaches or suggest any other solutions. Thank you.

Answer №2

I came across a great solution for this problem by creating a new scope array like so: $scope.fileNames = [];

Instead of using the input model directly, I replaced it with data-ng-model="fileNames[$index]"

This allowed me to retrieve the values by index using $scope.fileNames[index]

Here is how the code looks like now: https://jsfiddle.net/medoo/wgc1my7d/3/

HTML

<div data-ng-app="myApp" data-ng-controller="myCtrl">
        <table>
            <tr data-ng-repeat="oneFile in ShowFiles">
                <td style="border: 1px solid #000000">{{oneFile}}</td>
                <td style="border: 1px solid #000000">
                    <input data-ng-model="fileNames[$index]" type="text" style="width: 200px" />
                </td>
            </tr>
        </table>
        <input id="save" data-ng-click="save()" type="button" value="Save" />
        <div id="msg"></div>
    </div>

ANGULARJS

<script>
  var arr = ["~\\191746.JPG", "~\\191848.JPG", "~\\191908.JPG"];
  var app = angular.module("myApp", []);
    app.controller("myCtrl", function ($scope) {
     $scope.ShowFiles = arr;
      $scope.fileNames = [];

      $scope.save = function () {
    var msg = document.getElementById("msg");
    $scope.ShowFiles.forEach(function (oneFile, index) {
        msg.innerHTML =
        msg.innerHTML + 'row #' + (index + 1) + ': ' + JSON.stringify(oneFile) + ' --- ' + $scope.fileNames[index] + '<br />';
    });
};
}); 
</script>

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

How can values be passed to child components in Vue when using component tags for dynamically switching components?

Is there a way to pass values to children components in Vue when using the component tag? It appears that I am unable to pass values to a child component using the component tag without using v-if: <component :is="showNow"></component> ...

Cannot access jquery within an angular directive

I've been attempting to incorporate jquery-ui's sortable feature on the elements within an ng-repeat loop. The issue I'm facing is that I am unable to actually perform the sortable action on these ng-repeat elements. I have searched for so ...

Repetitive bouncing in a trampoline leads to the error message "Call stack has reached maximum size"

I have been delving into the world of blockchain and experimenting with a simple implementation of "proof of work". Proof of work: export function mineBlock(difficulty: number, block) { const prefix = Array(difficulty + 1).join("0"); function mine(b ...

How to animate a left border shifting to the center using JavaScript

As I'm modifying my current div, I need to add a vertical line in the center of it. I've come across various solutions where a left border is added and then shifted using the left property by 50% (which effectively places it in the middle). Here ...

How to update an Array<Object> State in ReactJS without causing mutation

In my program, I store an array of objects containing meta information. This is the format for each object. this.state.slotData [{ availability: boolean, id: number, car: { RegistrationNumber : string, ...

The jQuery datatable offers a convenient date function that allows for date manipulation in milliseconds format

Recently, I have been working on updating the task owner ID using a lookup field selection in my code. The tasks are displayed based on the selected date from a datepicker value under the query in the controller. However, I encountered an issue where the a ...

"Utilizing Javascript's Regex to selectively replace only the first character

Forgive me if this is a beginner question, but I'm really unsure about this. Is there a regex solution to replace a character that appears first in a string? For example: 12 13 14 15 51 41 31 21 All data where '1' is the first character s ...

Unable to retrieve real-time data from Firestore using getStaticPaths in Next.js

While fetching data from Firebase Firestore using getStaticProps is successful, I encounter a 404 page when attempting to implement the logic for retrieving details of individual items with getStaticPaths. The current state of my [id].js code appears as fo ...

AngularJS encounters a lack of 'Access-Control-Allow-Origin' header

I have encountered an issue with my AngularJS application. I am attempting to send data to a third-party URL for storage on their server. However, when I execute the code below, I receive the following error message: XMLHttpRequest cannot load . Response t ...

Struggling to locate images in Three.js

I'm facing a challenge with my Vue Cli app where I am attempting to use Three.js for rendering 3D objects within it. The issue arises when I attempt to load an image to utilize as a texture. let scene = new Three.Scene(); const spaceTexture = new Th ...

Changes made to code within the node_modules directory do not appear in the browser

I encountered a bug in the vuejs-datepicker project on Github, prompting me to fork the repository. However, despite making changes to the forked project, these alterations are not reflected in my main project that relies on this dependency. Here's a ...

Attempting to single out various entities within a JSON array through the use of radio buttons

I am currently developing a website to showcase sports teams' schedules. Each team has its own JSON file containing relevant information that I aim to display upon selecting the team from a radio button. For instance, let's consider the example ...

Maintaining the active status of section 1 after the page is refreshed using Javascript and CSS

I have a total of 3 buttons and 3 hidden sections available, which can be seen in the image below: click here for image description Whenever one of the buttons is clicked, the respective section transitions from being hidden to becoming visible: click he ...

Ways to send data to a popup in svelte

Hey there, I could really use some assistance with my Svelte app. I'm trying to implement a modal and pass a parameter to the modal component in order to customize its content. However, when using the open() function of Modal, we only need to provide ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...

Utilizing an object map to pass objects as props without losing their keys

I have an array of objects named obj, structured as follows: { "root": [ { "key": "mihome", "label": "home", "action": "url", ...

Difficulty in implementing jQuery accordion height style using either content or fill option

What I am looking for is to have only one specific div in my accordion (device properties) change its height based on the content. I have also noticed that if I use Firebug to remove the height property of the device div, it adjusts the height correctly. ...

Learn how to activate a JS native event listener using jQuery for the 'change' event

This question is unique from the one found at How to trigger jQuery change event in code. The focus here is on the interaction of jQuery with native event listeners, rather than jQuery event listeners. I am using addEventListener to bind a change event fo ...

AngularJS: Handling multiple asynchronous calls simultaneously in a function

In my AngularJS function, I need to make two asynchronous calls that are independent of each other. However, the function should only return when both calls have completed and the results are stored in the return variable. I have tried various solutions a ...