Once an item is added, the table vanishes into thin air

I have a DataTables setup to show a list of project names, and I have a button that should add an item to the displayed array. However, when I click the button, the table disappears.

Below is the code snippet:

view.html

<button ng-click="vm.add()">Add item</button>
<table datatable="ng" dt-instance="vm.dtInstance" dt-options="vm.dtOptions" dt-column-defs="vm.dtColumnDefs"
       class="table table-hover table-striped table-bordered table-condensed">
    <thead>
    <tr style="background-color: #00b3ee; color: white; border:none">
        <th style="text-align: center">Nom</th>
        <th style="text-align: center">Actions</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="project in vm.project.projects">
        <td style="width: 90%; vertical-align: middle">{{project}}</td>
        <td align="center" style="vertical-align: middle">
            <button data-toggle="modal" ng-click="vm.setProject(project)"
                    data-target="#deleteEureciaProjectModal" type="button" class="btn btn-danger">
                <i class="fa fa-trash">&nbsp;&nbsp;</i>Supprimer
            </button>
        </td>
    </tr>
    </tbody>
</table>

controller.js

vm.add = () => vm.project.projects.push('new project');

fetchProject().then(result => {
    vm.project = result;

    // vm.project = {
    //     projects: [
    //         "project1",
    //         "project2",
    //         "project3",
    //         "project4"
    //     ],
    //     etc...
    // }

    vm.project.projects.push("newProject"); //it's working here, which is normal

    //init datatable
    vm.dtInstance = {};
    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withBootstrap();
    vm.dtColumnDefs = [];
    for (var i = 0; i < 2; i++) {
        if (i == 1) {
            vm.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i).notSortable());
        } else {
            vm.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i));
        }
    }
})

I've attempted using objects instead of strings, but that didn't solve the issue. I'm unsure of what's causing this problem. I'm unable to utilize server-side processing, and I need to find a solution within Angular methods.

Answer №1

After some investigation, I managed to solve the issue:

By initializing vm.project.project before making the promise call, the problem was resolved. I created the vm.project object and added the project property to it with an empty array. This allowed me to add items without encountering the disappearing table issue.

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

Stripping CSS prefixes upon file initialization

When developing my application, I have a process in place where I load CSS files on the back-end using Express.JS and then transmit them to the front-end. However, before sending the CSS code to the front-end, I need to: Identify the user's browser; ...

Utilize JavaScript to parse and retrieve specific data from an SVG file in XML format

I am attempting to retrieve an svg file using jquery or javascript. Here is an example of the svg code: <svg width="111" height="123" xmlns="http://www.w3.org/2000/svg"> <g> <title>Layer 1</title> <rect fill="#ffffff" strok ...

having trouble installing vue on macOS using npm

Here are the steps you should follow: Instead of using node v14+, switch to node v10+. (IMPORTANT) Add the following paths to your ~/.zshrc file (if you use zsh): /Users/[yourUsername]/.npm-packages/bin /Users/[yourUsername]/.npm-global/bin After ...

ReactJs: difficulty in resetting input field to empty string

I have an application using React v 0.13.1 (Old version). I am struggling to update my input field to "" after retrieving the updated value from the database. Scenario: I am updating the input fields by clicking on the button named "Pull&qu ...

What is the reason behind having 3 watchers for 1 binding in AngularJS?

Take a moment to view the screenshot provided below In the screenshot, it is evident that there are #3 watchers for a single binding. Would someone care to explain the reason behind this? P.S: I am utilizing AngularJS Batarang to assess performance. ...

Extract all links from an external website

I'm attempting to extract all the URLs from a webpage using jQuery so that I can later use them with $.get(). If these URLs were located on the same page as the script, retrieving them would be easy by doing something like var links = document.getEle ...

I intend to extract the long_name value from the JSON data using AngularJS

I have been attempting to retrieve the long_name from the JSON data below using angular js, but unfortunately I am unable to successfully fetch it. CODE: { "results" : [ { "address_components" : [ { "long_name ...

Leverage JSON to display data retrieved from a database

My website allows users to input the title of a movie into a database using an input field. Now, I want to display that title on the front page of the website. I have created a template for displaying it: %div{"ng-repeat" => "movie in movies"} {{ mo ...

Can a form be submitted using an Ajax request triggered by a div element instead of an input type submit?

I used to submit the form by triggering $(".btn-update.").click() before, but now that I'm using $(".btn-update").ajaxForm(), the form is not getting submitted. Here is the HTML code: <form id="company-profile-edit-form" name="company-profile-edi ...

Ways to protect Ajax link requests

Picture this scenario: a user is trying to register on a website and is filling out a form. As the user fills in the form, jQuery continuously validates fields using regular expressions, checks if they are valid, etc. The email address serves as the prima ...

How to ensure a table in MaterialUI always maintains full width without requiring horizontal scrolling in CSS?

After attempting to allocate each widthPercent value on the TableHeader so they sum up to 100%, I am still experiencing the presence of a scroll bar. I have tried setting fixed widths for each column, but this results in excess space on the right side dep ...

Issue with document.referrer in Firefox: Unexpected behavior

I attempted to utilize the document.referrer function. It functions correctly in Google Chrome, however it does not yield the expected results in Mozilla Firefox. if (document.referrer.indexOf('stringToCheck') > 0) { //insert code here ...

Error encountered while running a mounted hook in Vue.js that was not properly handled

I have created a To Do List app where users can add tasks using a button. Each new task is added to the list with a checkbox and delete button next to it. I want to save all the values and checked information on the page (store it) whenever the page is ref ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

"Exploring the best way to retrieve the angular filter value within a Node.js environment

Currently, I am facing an issue with accessing the value in Node.js using req.body when it is stored in ng-model. The ng-model includes an AngularJS filter, and I need to retrieve this filtered value from the input field in Node.js through req.body. Below ...

Using a directive template to invoke a service method

Imagine you have a custom directive: <product> <img ng-src='{{someImage}}' /> </product> This directive is defined like this: app.directive("product", function() { return { scope: {}, restrict: 'E& ...

I am struggling to set a required input in Angular2

I am new to Angular and currently working on a project that requires input validation to ensure that no field is left blank. The project consists of an HTML file along with a .ts file for functionality. Below is a snippet from the HTML: <div class="f ...

Can we iterate through an array containing arrays of objects in a loop?

Here is an example of how I want my solution to appear: Currently, I have created an array where I group items by their first letter, like this: const grouped = _.groupBy(topicPages, key => key.relatedTopic.title[0]); Resulting in the following: Now, ...

The Node.js JSON string displays as "[object Object]" in the output

Front End // js / jquery var content = { info : 'this is info', extra : 'more info' } $.ajax({ type: 'POST', url: '/tosave', data: content }); Node // app.js app.post('/tosave', funct ...

Exploring the potential of utilizing functions in express.js to take advantage of the "locals"

Having experience with Rails/Sinatra, I am accustomed to using helper functions in my view files. However, incorporating this functionality into express.js has proven to be quite challenging. You can include locals automatically like this... app.set("nam ...