Learn the steps for incorporating a fresh item into a table from a pop-up interface with angularjs

I have been working on a simple customers table that includes information such as name, lastname, and age. I have successfully created a function that allows users to add a new customer, which is working fine. Additionally, I have implemented a pop-up window, but I am facing an issue with adding a new customer from it. Any assistance would be greatly appreciated. Thank you!

Below is the code that is currently working:

<script type="text/javascript">

var App = angular.module('sortApp', ['ui.bootstrap'])

App.controller('mainController', function($scope, $modal, $log, $filter) {
$scope.sortType = 'id'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchPerson = ''; // set the default search/filter term

// Array - List of People
$scope.People = [
{ id: 1, name: 'Mike', Lastname: 'White', age: 26 },
{ id: 2, name: 'Carl', Lastname: 'Barns', age: 41 },
{ id: 3, name: 'Deb', Lastname: 'McDonals', age: 78 },
{ id: 4, name: 'Tommy', Lastname: 'Humbs', age: 32 }
];

/*
This function adds a new customer
*/
$scope.addPerson = function(){
var customer = {
name: $scope.name,
Lastname: $scope.Lastname,
age: $scope.age,
};

$scope.People.push(customer);
};
/*
This function removes a customer
*/
$scope.removePerson = function(index){
$scope.People.splice(index, 1);
};
$scope.openPopupScreen = function() {

var modalInstance = $modal.open({
template: '<div class="modal-header"><a class="close" data-dismiss="modal" ng-click="cancel()">X</a><h1>Add Customer</h1></div><div class="modal-body"><form>' +
'<label>Name:</label><input type="text" class="span3" ng-model="name"></br>' +
'<label>Lastname:</label><input type="text" class="span3" ng-model="Lastname"></br>' +
'<label>Age:</label><input type="number" class="span3" ng-model="age"></br>' +
'<button type="submit" class="btn btn-success" ng-click="addPerson()">Add In List</button>' +
'<button type="reset" class="btn ">Clear</button>' +
'</form>' +
'</div>' +
'<div class="modal-footer">' +
'<a data-dismiss="modal" aria-hidden="true" class="btn btn-primary" ng-click="cancel()">close</a>' +
'</div>',
controller: ModalInstanceCtrl
});

};

var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};

$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};

});
</script>

Answer №1

You are encountering an issue in your modal because you are calling the addPerson() function which is located in the mainController, not in the modal controller.

To resolve this, you need to create a function in the modal controller to retrieve the result and pass it back to the main controller. For example, in ModalInstanceCtrl:

$scope.newPerson = {
   //Bind ng-model from modal input to properties of this
};

$scope.add = function() {
    //Pass newPerson back to the caller in the main controller
    $modalInstance.close($scope.newPerson);
};

Don't forget to bind the add() function to a button click:

<button type="button" class="btn btn-success" ng-click="add()">Add to List</button>

In the main controller:

var modalInstance = $modal.open({
   //Create the modal
});

modalInstance.result.then(function (newPerson) {
    $scope.addPerson(newPerson);
}, function () {
    //User clicks dismiss instead of add
});

Answer №2

Additionally, it is advisable to update the ng-model values within the form of your modal popup to something similar to "userData.username", "userData.email" and so forth. It is important to note that having an ng-model attribute without a 'dot' is considered incorrect. To address this issue, initialize an empty object called $scope.userData in your mainController. When adding new user data, assign the values such as username and email to this object.

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

Is it advisable to hold off until the document.onload event occurs?

I'm working with a basic HTML file where I need to generate SVGs based on data retrieved through an AJAX call. Do I need to ensure the document is fully loaded by enclosing my code within a document.onload = function() { ... } block, or can I assume ...

Unable to locate the script source. An internal server error 500 has occurred with the node and express-handlebars system

I'm encountering an annoying error 500 because my custom JavaScript scripts are not loading properly. I am currently running a local node.js server with express and express-handlebars. Below is my app.js file: const express = require('express&a ...

Tips for Embedding External JavaScript and URLs in Joomla Protostar Template

I'm interested in incorporating a hamburger menu into my Joomla protostar template, similar to the one featured on this URL: ['https://codepen.io/PaulVanO/pen/GgGeyE'] This will provide me with a fullscreen hamburger menu for both desktop ...

Transfer PHP's uniqid() function to real-time using JavaScript with jQuery

Seeking a compact JavaScript(jQuery) code snippet to achieve this: date("r",hexdec(substr(uniqid(),0,8))); Your assistance is highly appreciated. Thank you. ...

Having trouble locating and interacting with the textarea element in Salesforce using Selenium Webdriver

Encountering an issue with the Selenium Webdriver where it throws an error stating that the element is not visible and cannot be interacted with when attempting to access a textarea. 1. The textarea is located within a pop-up window, which can be accessed ...

AngularJS with ui-router for creating a lightbox overlay with the added functionality of deep linking

Exploring the implementation of AngularJS for creating a lightbox with URL deeplinks. The functionality works smoothly, however, assigning a name to it for every page along with the corresponding template is essential. To achieve this, I am utilizing ui-r ...

Updating Angular 2 components using BaobabWould you like to learn how to

Exploring Baobab as a potential solution for developing Flux applications with Angular 2 has piqued my interest, but I have yet to come across any examples. My primary query revolves around the process of 'subscribing' an Angular Component to Ba ...

Database-driven cron scheduling

How can I set up a cron job to send an email notification using node-mailer about 1 or 2 weeks before the expiration date of a product in my database that includes an expired_date field? ...

Tips for resizing a tooltip using CSS

I am currently working on customizing tooltips and would like them to display right below the hover text in a responsive manner, with the ability to have multiline text. Instead of spreading horizontally, I want the tooltip to expand vertically based on th ...

Warning on React component listing due to key issue originating from the parent component

Alert: It is essential that each child in a list has a distinct "key" prop. Please review the render method of ForwardRef(ListItem). A child from RecipientsList was passed. I have located this issue using the react-components debugger tool on Chrome. I ad ...

What is the best way to serialize data from non-form elements and make it easily accessible through params[:model]?

I have developed a unique Sinatra application that leverages an external API to load data and exhibit it on a page. Utilizing Sinatra, the information is retrieved and stored in a temporary model instance (which is NOT saved) for seamless access to all its ...

Using Vue-router and Typescript with beforeEnter guard - utilizing validated data techniques

As I utilize Vue along with vue-router and typescript, a common scenario arises where a single page is dedicated to displaying a Photo component. A route includes a beforeEnter guard that checks my store to verify the existence of the requested photo. ...

My page is experiencing delays due to setInterval

Currently, I am delving into the world of Chrome Extension development and am faced with a roadblock in replacing elements on a live chat page. While most of my tasks are running smoothly, the one thing causing issues is the setInterval option that trigger ...

Step-by-step guide on retrieving JSONP data from Angular service within view by utilizing expressions

I have been developing an Angular application that retrieves data from the Strava API. While experimenting with $http.get, I realized that separating the logic into a dedicated service would be more organized, allowing my controller to simply call the serv ...

bootstrap used for creating horizontal radio buttons

I'm attempting to horizontally align radio buttons within a form without relying on the Bootstrap library. The following code achieves this: <form id="test_form"> <div class="control-group"> <label for="Q1">First question</ ...

JavaScript: Finding the full Base-URL - A Step-by-Step Guide

Is there a way to incorporate JavaScript into external files without relying on the use of base/root URLs in HTML/PHP templates? Everything is functioning properly except for the need to determine the base/root URL in an included JS file. Dilemma: I am se ...

React's useState Hook: Modifying Values

I just started learning about React and React hooks, and I'm trying to figure out how to reset the value in useState back to default when new filters are selected. const [apartments, setApartments] = React.useState([]) const [page, setPage] = React.us ...

Struggling to pass two objects as props and have them be equated to one another

I have a scenario where I am passing a worker object as a prop to the view.vue field. In the mounted method of the component, I am trying to assign this worker object to the manager object. However, when I use the assignment `this.manager = this.worker`, i ...

Unable to retrieve the most recent global variable value within the confirmation box

<script type="text/javascript"> var customDiv ="hello"; $(function () { var $form = $("#authNotificationForm"); var startItems = $form.serializeArray(); startItems = convertSerializedArrayToHash(startItems); $("#authNoti ...

I am able to input data into other fields in mongoDB, however, I am unable to input the

I am facing an issue with the password while everything else seems to be working fine. I am using a schema and getting an error, but it could be a problem in my functions because I hashed the password. I am unable to identify what's causing the issue. ...