Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface:

interface Person {
    Id: number;
    FirstName: string;
    LastName: string;
    Age: number;
}

Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. An example element inside the form looks like this:

<input id="FirstName" name="FirstName" type="text" class="form-control" ng-model="FirstName" placeholder="Enter First Name" />

I want to be able to map the form values to the object argument in the submit call like so:

$scope.submit = (person: MyApp.Models.Person) => {
  //Access person values
}

The issue arises when inspecting the person value within the submit(); it comes up as undefined and not populated.

I am curious if it's feasible to automatically use and bind the multiple <input> form values from within the form element directly to the object argument known by TypeScript in the submit() method?

It might be that this is simply not possible, but I would like to inquire before resorting to manually retrieving each ng-model value and constructing a Person instance within the submit() function.

Answer №1

Yes, it is definitely possible. In fact, some experts even recommend this strategy.

Instead of directly using the members of the person object in your form elements (ng-model=FirstName), it's better to use dot notation with a person object (ng-model=person.FirstName). For instance, in your scope object:

$scope.person: MyApp.Models.Person;

and in your HTML markup (notice the difference in your ng-model):

<input id="FirstName" name="FirstName" type="text" class="form-control" ng-model="person.FirstName" placeholder="Enter First Name" />

By doing this, when you invoke your submit function, you can pass it the person model

ng-submit="submit(person)"

and within your submit function, the person parameter will have access to all the properties of the person object defined on your form.

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 is the optimal approach for managing server-side data stored as a JavaScript variable?

When dealing with global variables like JSON inserted into a web page server side with PHP, the best way to handle it is up for debate. Options might include leaving it for garbage collection, omitting var initialization and deleting the variable, or simpl ...

Is it recommended to use separate Controllers for each tab in Angular JS to load the pane?

Recently delving into the world of Angular JS and eagerly seeking expert advice and suggestions. Would it be advisable to use separate controllers for initializing each Tab to load the Pane content? Is assigning separate controllers a recommended approac ...

Unit testing in AngularJS: Initializing the controller scope of a directive

Here is the code for a directive with a separate controller using the "controller as" syntax: 'use strict'; angular.module('directives.featuredTable', []) .controller('FeaturedTableCtrl', ['$scope', function ($sco ...

Tips for exporting data to a JSON file using the Google Play Scraper in NodeJS

Recently, I've been exploring the Google Play Scraper and I'm in need of a complete list of all appIds using NodeJS. The issue I'm facing is that it only outputs to console.log. What I really require is to save this output to JSON and then c ...

Learn how to leverage the drag and drop directive in AngularJS for your web

I integrated drag and drop functionality into my project using: https://github.com/marceljuenemann/angular-drag-and-drop-lists This is how I implemented it: <div ng-repeat="list in lists"> <div style="float: left; margin-left: 5px;"> ...

Looking for suggestions on AngularJS and Rails integration!

I'm currently in the process of creating a website using rails, but I want to integrate AngularJS for several reasons: Efficient sorting between 2 different types of data (such as selecting various restaurants from a list and then different food cate ...

Access-Control-Allow-Methods does not allow the use of Method PUT in the preflight response, as stated by Firebase Cloud Functions

I am facing an issue with my Firebase cloud function endpoint. I have a setup where it forwards PUT requests to another API endpoint. I have configured the following Access-Control-Allow- headers: // src/middlewares/enableCORS.ts export default function en ...

Attempting to employ the .reduce method on an object

Currently, I am faced with the task of summing a nested value for all objects within an object. The structure of my object is as follows: const json = [ { "other_sum": "1", "summary": { "calculations" ...

Change the ddmmyy date string to dd/mm/yyyy format using TypeScript

When I use the date picker onchange method, the date is passed as a string like ddmmyyyy (20102020) to dd/mm/yyyy. I am unsure of how to convert the date format from ddmmyyyy to dd/mm/yyyy. In the CustomDateParserFormatter, the string needs to be converted ...

Error: Syntax mishap detected - Oh dear

Recently, I've been developing a small slideshow / public display for a client using the HTML5 Rock's Slideshow code. Everything was going smoothly until I encountered a DOM Exception 12 - an error related to CSS selectors. Strangely, I couldn&ap ...

What could be causing React to throw an error?

Check out this React Component: GeneralInformation = React.createClass({ totalCaptialRaisedPanel: function() { var offeringInfo = this.props.company.data.offerings.data[0]; var percentageComplete = (offeringInfo.capital_raised / offer ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...

Sending data to a PHP page to maintain state in an Angular application

Here is my current setup: In a dynamic Angular environment, I have various states connected to PHP pages. These PHP pages rely on specific data variables, typically provided as GET parameters outside of Angular. Now, I am looking for a way to switch to a ...

Error Message: "Module not found - Module TS2307 cannot be located

When I try to open a Typescript project in VSCode, I encounter the error message "ts2307 Cannot find module 'react' or its corresponding type declarations". However, everything works fine when I use WebStorm. The project was created using Create ...

Is it considered poor form for an Angular controller to invoke a function on a directive?

My custom Angular directive functions as a unique combobox, where clicking on the input control reveals a div below it with a list of items from a model object. The user can type text into the input control to filter the displayed list. In addition to the ...

Tactics for postponing a js function post-click

I need to implement a delay after clicking a button to fetch some data. The code will be executed within the browser console. $(pages()) is used to retrieve the pagination buttons. let calls = []; for (let i = 1; i <= callPagesCount; i++) { ...

import an external JavaScript file in an HTML document

Looking to load a .js file from a simple HTML file? If you have these files in the same folder: start.js var http = require('http'); var fs = require('fs'); http.createServer(function (req, response) { fs.readFile('index.htm ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Converting Excel files into JSON format with AngularJS

Seeking guidance on integrating a feature where users can upload an excel file from their device and have it converted to JSON format. Previous functionality allows for csv uploads to be converted, but now looking to enable excel conversions. Any tips or ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...