Issue Adding a Row to a Table in AngularJS

I need assistance with dynamically adding the information entered in a form to a table.

Below is the HTML form:

 <section id="contact-info">


    <section id="contact-page">
        <div class="container">
            <div class="center">        

                <p class="lead">Import reports</p>
            </div> 
            <div class="row contact-wrap"> 
                <div class="status alert alert-success" style="display: none"></div>
                <form id="main-contact-form" class="contact-form" name="contact-form" method="POST" enctype="multipart/form-data" >
                    <div class="col-sm-5 col-sm-offset-1">
                        <div class="form-group">
                            <label>name *</label>
                            <input type="text" name="NameOfUploader" class="form-control" required="required" ng-model="r.NameOfUploader">
                        </div>
                       <div class="form-group">  
                            <label>DateOfUploade</label>
                            <input type="Date" class="form-control" ng-model="r.DateOfUpload" >
                        </div>
                            <div class="form-group">
                                <label for="t">Type of File</label>
                                <select 
                                    class="form-control" id="t" ng-model="r.TypeOfFile">
                                    <option>.word</option>
                                    <option>.xsl</option>
                                    <option>.pdf</option>
                                </select>
                            </div> 

                            <div class="form-group">
                            <label>file</label>
                            <input type="file" name="file" class="form-control" fileread="r.file">
                        </div>                        

                        <div class="form-group">
                            <button type="submit"  class="btn btn-primary btn-lg"  ng-click="saveDetails()">Import File</button>
                        </div>
                                    <table class="table">
                            <tr>
                                <th>Id_file</th>
                                <th>NameOfUploader</th>
                                <th>DateOfUpload</th>
                                <th>TypeOfFile</th>
                                <th>File</th>
                            </tr>
                            <tr ng-repeat="r in reports">
                                <td></td>
                                <td>{{r.NameOfUploader}}</td>
                                <td>{{r.DateOfUpload}}</td>
                                <td>{{r.TypeOfFile}}</td>
                                <td>{{r.file}}</td>
                            </tr>
                        </table>   

                    </div> 


                    </form> 
            </div><!--/.row-->
        </div><!--/.container-->
    </section><!--/#contact-page-->

Here's my Java controller code:

@RequestMapping(value="/saveDetails")
    public DetailsReport saveDetails(DetailsReport d)
    {
        detailsReportRepository.save(d);
        System.out.println(d.toString());
        return  d;

    }

And here's the JavaScript controller code:

 //Save details of report

    $scope.saveDetails=function(){

          var fd = new FormData();
          var url='http://localhost:8080/saveDetails';
          fd.append("NameOfUploader",$scope.r.NameOfUploader);
          fd.append("DateOfUpload",$scope.r.DateOfUpload);
          fd.append("TypeOfFile",$scope.r.TypeOfFile);
          fd.append("file", $scope.r.file);

         console.log(fd);
         $http.get(url,fd,{
             transformRequest: angular.identity,
             headers: {'Content-Type': undefined}
         })
         .success(function(data){

             $scope.reports.push(data);
            console.log(data);
             console.log($scope.reports);

         })
         .error(function(){
         });


    }

If anyone can help, I am facing an issue where the imported data is not being added to the table when clicking on "Import File". There are no errors reported.

Answer №1

It is possible that there is a discrepancy in the mapping of 'data' and the '$scope.reports' variable.

Could you kindly share the logs for both of these values?

Answer №2

Feel free to check out this solution

AngularJS: Updating ng-repeat list when deleting an element from the model array

Simply implement $scope.$apply()

Answer №3

Based on my interpretation of the console output, it seems like the issue lies in adding an array with one element to $scope.reports instead of an object. This results in an empty row being displayed because there is no matching data for the r element.

To resolve this problem, you need to individually add elements if it's an array in your controller.

//Save details of report
$scope.saveDetails=function(){

    var fd = new FormData();
    var url='http://localhost:8080/saveDetails';
    fd.append("NameOfUploader",$scope.r.NameOfUploader);
    fd.append("DateOfUpload",$scope.r.DateOfUpload);
    fd.append("TypeOfFile",$scope.r.TypeOfFile);
    fd.append("file", $scope.r.file);

    console.log(fd);
    http.get(url,fd,{
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(data){
        if (data instanceof Array){
            for (i = 0; i<data.length; i++){
                $scope.reports.push(data[i]);
            }
        } else {
            $scope.reports.push(data);
        }
        console.log(data);
        console.log($scope.reports);
    })
    .error(function(){
    });
}

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

using a variable with conditional statement in jQuery

Having trouble applying a var to a statement when certain conditions are met. The current syntax isn't showing errors, but it's not functioning as expected. <script type="text/javascript> $(document).ready(function(){ var action_is_post ...

`Troubleshooting Three.js webglrenderer.render problem`

I am currently working on a website using three.js and Nuxt.js. However, I have encountered an issue when trying to implement the EffectComposer. The console is showing numerous warnings like: three.webglrenderer.render(): the rendertarget argument has be ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

Utilizing a React Hook to set data by creating a pure function that incorporates previous data using a thorough deep comparison methodology

I have come across the following code snippet: export function CurrentUserProvider({ children }) { const [data, setData] = useState(undefined); return ( <CurrentUserContext.Provider value={{ data, setData, }} & ...

Header input for searching in a different section of the page

I am working on a project where I have a Header component containing an Input element. My goal is to search within an array located in another component, specifically the product list component. Both of these components are connected through App.js. How ...

The node path.relative function is providing inaccurate path information

It seems like there might be an issue with the output of path.relative in Node. When I run the function with 'a/file.js' and 'a/file.css', it returns '../file.css' instead of './file.css'. This is causing confusion f ...

combine string inputs when ng-click is triggered

Is there a way to pass a concatenated string using ng-click to MyFunction(param: string)? I have tried but so far, no luck: <input id="MeasurementValue_{{sample.Number}}_{{$index}}" ng-click="Vm.MyFunction('MeasurementValue_{{sample.Number ...

What could be causing the issue of images not loading in Chrome while they are loading perfectly in Mozilla when using CSS3?

Recently, I dove into a project utilizing react with webpack, and everything was smooth sailing until I encountered the CSS hurdle. Despite successfully configuring webpack, trouble brewed when it came to styling. Specifically, setting the background image ...

Deciphering the $resource factory along with the @ symbol prefix

Under this particular service: vdgServices.factory('UserService', ['$resource', function($resource) { return $resource('api/users/:id', {}, { doGet: { method: 'GET', params: { i ...

What is the best method for uploading an image, video, or audio to Tumblr's API?

I've successfully shared quotes, texts, and links using Tumblr's API. However, I'm now curious about the process of posting images, videos, and audio through their API. While posting from a web URL seems straightforward, I am unsure of how t ...

Sending a JavaScript array to a Ruby on Rails controller by utilizing a hidden form field

Having explored numerous solutions that did not fit or resolve my issue, I am turning to this platform with my question: I utilize JavaScript to populate hidden fields in a form with data and transmit it to a Ruby on Rails controller. While this process w ...

The absence of onreadystatechange() on XMLHttpRequest objects is proving to be problematic

(function (updateSend) { XMLHttpRequest.prototype.send = function () { console.log(this.onreadystatechange); //null updateSend.apply(this, arguments); }; })(XMLHttpRequest.prototype.send); Why does this.onreadystatechange ev ...

Can the title of a page be modified without using HTML?

Is it possible to update the title of my website directly from the app.js file? (I am utilizing node.js and express.js) ...

Issue with nested directive not triggering upon page load

I recently started working with AngularJS and came across an issue with nested directives. In my project, I have two directives: MainDir.js (function(){angular.module("mod").directive("mainDir", function(){ return { restrict: "E", scope: {}, ...

Issue with the rendering of the Google Font "Playfair Display" involving the letters "ff" being displayed incorrectly

There seems to be a problem with the Google Font "Playfair Display" when two consecutive "f" characters are used. Check out this example of the odd rendering issue My idea for a fix involves creating a JavaScript function that scans all text on the websi ...

Guide for transforming an existing AngularJS 2 web application into a Cordova application

I am in the process of building a webapp using AngularJS 2.0 and now I want to convert it into an Android apk so that I can install it on my Android phone for testing. I have no prior experience with developing mobile native apps or converting webapps int ...

Dynamic RSS Aggregator

I'm interested in developing a simple application that can retrieve RSS feeds from any feed URL. Can anyone provide me with some basic guidance on how to accomplish this? I'm fairly new to AJAX and similar technologies, so any assistance would b ...

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...

React component tirelessly retrieving and refreshing data without purpose

Currently, I have a react component that fetches data continuously for visualization purposes. This constant fetching is unnecessary and I am looking for a way to optimize it. The structure of my component is as follows: export default function Analytics( ...

Using jQuery to transfer variables across pages for displaying images

I have two HTML files named one.html and two.html. In the two.html file, there is a query string that displays images based on the value set in jQuery. Sample of two.html (for some reason it's not working on jsfiddle but works fine locally.) HTML & ...