Creating a versatile "add new entry" form in Angular that appends a new record to the parent scope

In my Angular application setup, I have an "Edit Invitation" state where a single invitation is scoped. This invitation contains a list of guests controlled by a guestList controller and iterated over in the view.

<div ng-controller="guestListCtrl as guestList">
    <div ng-repeat="guest in invitation.guests">
    {{ guest.name }}
    </div>
</div>

At the end of the guest list, there is a button to add a new guest. Clicking this button toggles a small form for users to save a new guest record.

<form name="addGuest" class="form" ng-submit="addGuest.$valid && guestList.addGuest(guestList.newGuest)" novalidation>

The controller successfully handles adding a new guest and pushing it onto its parent scope, guestList.guests.

However, on the Admin page, I have a similar setup with a guestList controller displaying a list of guests and allowing for adding a new guest through the same form. The HTML structure here differs significantly - utilizing different elements, CSS classes, and a directive for field editing by admins.

My query is whether there is a way to extract the "add new record" functionality into its own partial or directive to avoid rewriting the form and logic each time.

One potential solution could be creating an element directive:

<new-guest></new-guest>

Below is the directive implementation:

angular.module('app.directives').directive('newGuest', ['Guest', '$stateParams', function(Guest, $stateParams){
  return {
    restrict: 'E',
    transclude: true,
    templateUrl: 'directives/new-guest.html',
    bindToController: true,
    controllerAs: 'newGuestCtrl',
    controller: function() {
      var vm = this
      vm.newGuest = { "invitation_id": $stateParams.id };

      vm.addGuest = function(newGuest){
        Guest.create({guest: newGuest}, function(response) {
          //push new guest onto parent scope here
        });
        vm.newGuest = {};
      };

    }
  }
}]);

The directive effectively adds records to the database but struggles to push the new data onto the parent scope outside the directive (guestList.guests). One possible approach would involve creating a new directive housing the guest list and pushing onto that directive's scope, but this may not be ideal considering the distinct HTML structures used for Admin and User versions of the guest list.

Answer №1

1) Incorporate the guest list into your directive with two-way binding:

scope: {
    list: '='
}

By adding this to your directive definition, you establish the connection.

<new-guest list="guestList.guests"></new-guest>

This feeds the directive tag with the guest list data.

2) Implement adding a new guest in your callback function as suggested:

scope.list.push(newGuest);

By following these steps, you can ensure that the guestList.guests remains current.

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

What potential problem is arising from Jest's use of "transformIgnorePatterns" and how does it impact importing scoped CSS in a React application?

Currently facing a challenge with Jest testing in my React application following the addition of transformIgnorePatterns to the Jest settings. The default settings I included in the "jest" section of the root package.json file are as follows: "transfo ...

Emphasize a checkbox by selecting it when another checkbox is checked

I have a question about checkboxes and highlighting the checkmarks. The issue I am facing is that I have multiple checkboxes with the same ID for different screen resolutions. When I click on the label for "Check 1" it highlights the corresponding checkmar ...

Struggling to remove an image while using the onmouseover event with a button?

I am encountering an issue with hiding an image using the onmouseover event not applied directly to it, but rather to a button element. The desired functionality is for the image to appear when the mouse hovers over and disappear when it moves away. Here&a ...

Adjusting the scope value following the completion of an HTTP request in AngularJS

I have a controller where I am making an ajax call to fetch some data. After the successful callback, I assign values to $scope variable as shown below. $http.get(GlobalService.getDomainUrl() +'/hosts/attr').success(function(data){ //Afte ...

Attempting to display the todo item in the form of <li>, however, the todo.name property is not

I am currently developing a task manager application and have encountered a puzzling issue: When I include the Todo component within the TodoList component and pass the todo item as a prop todo = {name: "ssss", status: false, id: 0.0289828650088 ...

Uncovering the websocket URL with NestJS and conducting postman tests: A step-by-step guide

Creating a mean stack application using NestJS involves utilizing websockets. However, testing websockets in Postman can be confusing. Typically, I test route URLs in Postman and get output like: "http://localhost:3000/{routeUrl}". But when it comes to tes ...

Adjust the hue of a Three.js world map

Check out this awesome Three.js demo with a 3D Globe: I've been trying to modify the color of the globe from black to navy blue, but despite my efforts in editing the source files, I haven't been successful in changing its appearance. My unders ...

The Jquery .each() method is causing the return value to be undefined

Why is the getColorOptionSelect() function returning an undefined value, even though it has a value when checked with the debugger? I am certain that this issue is related to scope - my apologies for my lack of knowledge in JavaScript. jQuery(document).r ...

Formatting a ui-grid grid column in RC 3.0 to display currency

The options for the grid displayed below are meeting expectations in terms of data presentation. However, when attempting to format the value of row.entity[col.field] in my cellTemplate, I am not getting any data returned. Here is the code snippet: $scop ...

How can I set up flat-pickr for date and time input with Vue.js?

I'm currently working with flat-pickr. Let's dive into the configuration part of it. I have a start date field and an end date field. My goal is to make it so that when a time is selected in the start date field, it defaults to 12h AM, and when a ...

Sorting arrays in javascript

My JavaScript array is structured like this: var data_tab = [[1,id_1001],[4,id_1004],[3,id_1003],[2,id_1002],[5,id_1005]] I am looking to organize and sort them based on the first value in each pair: 1,id_1001 2,id_1002 3,id_1003 4,id_1004 5,id_1005 ...

What is the best way to save inputted names as properties of an object and assign the corresponding input values as the values of those properties?

I am searching for a way to dynamically build an object where each property corresponds to the name of an input field and the value of that property is the input's value. Here is the HTML structure: <form> <fieldset> ...

Display data from a JSON array in an HTML table by utilizing the ng-if directive

I have a JSON array that looks like this: $scope.array =[{"id":"1","age":"3","name":"ab"},{"id":"2","age":"2","name":"ee"},{"id":"3","age":"1","name":"dd"}]; I want to display this data in a table using ng-if, where each cell will only show data related ...

Instructions for passing the chosen value to Django

I am struggling to set up a search button using Ajax and Django. I need to send the selected value to the server, but I can't seem to retrieve the value from the select HTML tag. The variable value always ends up empty ({"obj":""}). Any ideas? HTML : ...

Refresh a div using jQuery and include PHP files for dynamic content updating

This is the code I am using to dynamically update divs containing PHP files: $(document).ready(function() { setInterval(function() { $('#ContentLeft').load('live_stats1.php').fadeIn("slow"); $('#ContentRight').load( ...

invoking a JavaScript function from an HTML file

I want to create a JavaScript server on Raspbian that not only serves .html content to the browser but also allows for user input through events like button clicks. Both my .html and .js files are located in the same directory, and I have used absolute pat ...

CSS responsive design: concealing elements does not prevent the page from being displayed

Imagine a scenario where I need to display a template in two different versions based on the user's device. For instance, I have utilized the following code: <div class="desktop"> <body> Hi Desktop user </body> </div> ...

Utilizing the Onchange Event with Multiple Input Fields in Vanilla JavaScript

I'm working on a website where multiple inputs need to be created dynamically using createElement. Each input can have its own class, id, and other attributes. The main objective is to automatically calculate the overall price whenever a user adds a ...

The additional values inserted into the form using jQuery are not being recognized or passed to AngularJS

My form has multiple input fields, some of which are pre-populated when the markup is generated. For example, value=#{ session[:lat] } or simply value='111'. While this appears correct when inspecting the page, Angular does not submit this value. ...

What is the process for saving information to a database with JavaScript?

I am currently utilizing the Google Maps API for address translation, primarily through the use of a geocoder. I am interested in saving these results to a local database for future reference, as there are limitations on the total number and frequency of ...