Creating an interactive table with AngularJS

Hello, I am a newcomer to Angularjs and I am facing an issue with creating a dynamic table. Unfortunately, the table is not being generated and upon further investigation, I noticed that the form submit functionality is also not working as expected. Please take a look at my code and provide me with some guidance.

<script>
    var app =angular.module("myApp",[]);
    app.controller("myCtrl",function($scope) { 
        $scope.students = [{
            'name' : 'ab',
            'email' : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfaead8fa8a2aea6a3e1aca0a2">[email protected]</a>',
            'dept' : 'cse' 
        }];

        $scope.addStudent = function(){
            console.log('addStudent');
            $scope.students.push( {
                'name' : $scope.name,
                'email' : $scope.email,
                'dept' : $scope.dept
            });
            $scope.name = '';   
            $scope.email = '';
            $scope.dept = '';
        };

    });
</script>

Below is the corresponding HTML code.

<body>
    <div ng-app = "myApp" controller="myCtrl">
        <div class = "form-group" >
             <form class = "student-form" ng-submit="addStudent()">
                <div class = "row">
                    <label class = "col-md-6" for= "name"> Name :</label>
                    <input class = "col-md-6" type ="text" ng-model="name"  class="validate" required>
                </div>
                <div class = "row">
                    <label class = "col-md-6" for= "email"> Email :</label>
                    <input class = "col-md-6" type ="email" ng-model="email" class="validate" required>
                </div>
                <div class = "row" >
                    <label for= "dept" class = "col-md-6"> Department :</label>
                    <input class = "col-md-6" type ="text" ng-model="dept" class="validate" required>
                </div>
                <div class = "row"> 
                <!--    <button type="button" class="btn btn-success col-sm-6" ng-click= addStudent()>Add</button>          
                        <button type="button" class="btn btn-danger col-sm-6" ng-click = reset()>Reset</button>         -->
                    <input type="submit" value="Submit" class="btn btn-success"/>
                </div>  
                {{name + ' ' + email +' ' + dept }}

             </form>
        </div>

        <div class = "table-responsive">

            <table class="table">
                <thead >
                    <tr class="success">
                        <td> Name </td>
                        <td> Email</td>
                        <td> Department </td>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="x in students">
                        <td>{{ x.name }}</td>
                        <td>{{ x.email }}</td>
                        <td>{{ x.dept }}</td>
                    </tr>
                <tbody>
            </table>                
        </div>
    </div>

</body>

Answer №1

There is a small error in your code.
Try using ng-controller instead of controller for it to function correctly.

Answer №2

   This is a sample code snippet demonstrating the use of AngularJS directives ng-app & ng-controller in an HTML file.
   
   In the HTML:
    
let's first include necessary dependencies:
 - Bootstrap CSS from a CDN
 - jQuery from a CDN
 - Bootstrap JavaScript from a CDN
 - AngularJS from a CDN

Then we define our main app module and controller in the script tags at the end of the body section.

In the Controller CompanyCtrl code in controller.js, we have defined a simple function to add rows dynamically to a table when a form is submitted.

The directive ng-repeat is used to loop through an array of companies and display their information in a table row format.

Finally, the directive ng-submit allows the form data to be submitted using the addRow() function defined earlier.

Feel free to modify and customize this code snippet to suit your application needs!

Answer №3

    <body>
        <div ng-app = "myApp" ng-controller="myCtrl">
        <div class = "form-group" >
             <form ng-submit="addStudent()" class = "student-form">
                <div class = "row">
                    <label class = "col-md-6" for= "name"> Name :</label>
                    <input class = "col-md-6" type ="text" ng-model="user.name"  class="validate" required>
                </div>
                <div class = "row">
                    <label class = "col-md-6" for= "email"> Email :</label>
                    <input class = "col-md-6" type ="email" ng-model="user.email" class="validate" required>
                </div>
                <div class = "row" >
                    <label for= "dept" class = "col-md-6"> Department :</label>
                    <input class = "col-md-6" type ="text" ng-model="user.dept" class="validate" required>
                </div>
                <div class = "row"> 
                <!--    <button type="button" class="btn btn-success col-sm-6" ng-click= addStudent()>Add</button>          
                        <button type="button" class="btn btn-danger col-sm-6" ng-click = reset()>Reset</button>         -->
                    <input type="submit" value="Submit" class="btn btn-success"/>
                </div>  
                {{name + ' ' + email +' ' + dept }}

             </form>
        </div>

        <div class = ""table-responsive">

            <table class="table">
                <thead >
                    <tr class="success">
                        <td> Name </td>
                        <td> Email</td>
                        <td> Department </td>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="x in students">
                    <td>{{ x.name }}</td>
                    <td>{{ x.email }}</td>
                    <td>{{ x.dept }}</td>
                    </tr>
                <tbody>
            </table>                
        </div>

    </body>

JS:

<script>
    var app =angular.module("myApp",[]);
    app.controller("myCtrl",function($scope) { 
        $scope.students = [{
            'name' : 'ab',
            'email' : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72131032151f131b1e5c111d1f">[email protected]</a>',
            'dept' : 'cse' 
        }];

      $scope.user = {};

        $scope.addStudent = function(){
            console.log('addStudent');
            $scope.students.push($scope.user);
            $scope.user = {};
        };

    });
</script>

This solution creates a form where users can input their name, email, and department. The data is stored in an object and displayed in a table using AngularJS.

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

Can a single endpoint be used to provide files to web browsers and data to REST requests simultaneously?

I recently completed a tutorial that lasted 7 hours on creating a blog, following it almost completely. The only step I skipped was setting up separate client/server hosting as suggested in the tutorial. Instead, I have a single Heroku server serving the c ...

Capture an image from the webcam without any manual intervention and store it in the system's directories

Looking to automate the process of capturing a picture from a webcam once access is granted, and then saving it without any user intervention. I've managed to capture the image but struggling with: A) Automating the capture process B) Saving the ca ...

Filtering data from Arduino using web serial communication

My setup consists of an Arduino kit connected to a webserial API that sends data to an HTML div identified by the id 'target'. Currently, all the data is being logged into one stream despite having multiple dials and switches on the Arduino. Th ...

Sending specific names as properties

Looking to streamline my repetitive form inputs by abstracting them into a component, I want the following functionality: <InputElement title="someTitle" v-model="someName" @blur="someFunction" name="someName" type="someType"> The desired output wo ...

Incorporate JSON into the selection choices

After working with PHP for a while, I decided to start learning how to work with JSON. I managed to successfully create a PHP file that returns JSON data. In my main file, I referenced the PHP file and was able to retrieve the JSON objects. One of the thi ...

Tips for successfully using a string with a slash ("/") as a parameter in a route within vue.js

Currently, I am utilizing Vue Router with a specific route setup { path: '/my-route/:param?', component: MyComponent } To link to this route, I have created the following link <router-link :to="'/my-route/'+myParam">Link text&l ...

Is it possible for jQuery to fail within an object method?

Consider this scenario: function Schedule (foo) { this.foo = foo; this.bar = function() { $.ajax({ url: '/something/', method: "GET", dataType: "JSON" }).done (function(data){ ...

What methods can be utilized to effectively showcase and modify exclusively the keys within a nested JSON structure?

I am working with a JSON structure that looks like the image linked below. I want to extract and rename only the yellow highlighted keys, then store them in a new array. Here are the key renaming requirements: act = Actual prognosis = Prog plan = Plann ...

Utilizing JSON and Javascript to dynamically generate and populate interactive tables

Here's how I've structured my JSON data to define a table: var arrTable = [{"table": "tblConfig", "def": [{"column": "Property", "type": "TEXT NOT NULL"}, {"column": "Value", "type": "TEXT NOT NULL"}], "data": [{"Property ...

The MediaStream Recording API is failing to capture video from the canvas element

I have been attempting to record and download video from a canvas element using the official MediaStream Recording API <!DOCTYPE html> <html> <body> <h1>Testing mediaRecorder</h1> <canvas id="myCanvas" w ...

Creating an HTML element that can zoom, using dimensions specified in percentages but appearing as if they were specified in pixels

This question may seem simple, but I have been searching for an answer and haven't found one yet. Imagine we have an HTML element with dimensions specified in pixels: <div style="width:750px; height: 250px"></div> We can easily resize i ...

Is it possible to utilize a controller within a page by referencing its controller ID?

In my project, I am facing an issue where multiple HTML pages are linking to each other and duplicating the same controller each time a new page is opened. This results in each page using its own controller, causing data saved in the previous controller to ...

Updating the content within the main body of the page rather than the sidebar in react-router v5

I have a question regarding the functioning of my sidebar and content. So, when I click on any item in the sidebar, the content changes accordingly. But what if I want to change the route directly from the content itself? That's where I'm facing ...

What Are the Possible Use Cases for Template Engine in Angular 2?

For the development of a large single page application (SPA) with Angular 2.0, I have decided to utilize a template engine like JADE/PUG in order to enhance clarity and clean up the code. My goal is to achieve optimal performance for the application. Th ...

Sharing my separately loaded HTML with React - a step-by-step guide

Separating JavaScript and HTML in React is important to me. I prefer to keep them distinct rather than mixing them together. That's why I've started creating my component files with a .js extension. For example, teachersList.js looks like this: ...

Using an array in ExpressJS to access JSON data

When I send JSON data via jQuery on a webpage, it appears as follows: $.post('/url', data); The data is a JavaScript object with values and an array. The JSON.stringify(data) output looks like this: {"favoriteAnimal":"piglet", "okayAnimals":[" ...

Display the last 3 characters of an input field when it is in focus

I want the minutes in my input to only show up when the input is focused. Can this be achieved? Currently, I am using jQuery to display the full time, but I prefer to always have the full time as the value and only show what is necessary. Another issue i ...

Exploring the possibilities of integrating Angular's $http get method with ASP.Net Web API

I am trying to utilize an asp web api to fill up an html table using angular. Everything functions properly when I debug in Firefox (I assume because the web service is returned in json), but in IE and Chrome it doesn't load (because the web service r ...

Angularjs is capable of successfully performing GET requests with JSON data, but encountering difficulties when trying to execute

I'm still getting the hang of using angularjs. I've been working with some JSON data and running into an issue with my post command. The get request is functioning perfectly, but any other type of request results in a 404 url error even though I& ...

Sending information to sequelize via table in express

I have implemented a setup in my postgresql database where users can follow each other by using a through table. as: 'follower', through: 'follow', foreignKey: 'follower_id' }) User.belongsToMany(User, { as: ...