Angular encountering issue binding array in $http POST request

Currently, I am in the process of setting up a post function using Angular. The HTML form I have includes two text boxes for user input and a drop-down menu for selecting from a number of choices. While binding the text boxes is not an issue, I am facing difficulty in binding the options in my array as choices in the drop-down menu.

If you'd like to see what I'm working on, here is a fiddle: http://jsfiddle.net/gtv7s8h3/2/

Form:

<form>
<input type="text" id="name" ng-model="myForm.Title" ng-minlength="5" ng-maxlength="20"> title <br/>
<input type="text" id="name" ng-model="myForm.Content" ng-minlength="5" ng-maxlength="20"> content <br />

<select ng-model="CategoryId" ng-options="item.name for item in CategoryId"></select>

<button ng-click="myForm.submitTheForm()">Submit Form</button>
</form>

Angular POST:

 angular.module("myapp", [])
 .controller("MyController", function($scope, $http) {
  $scope.myForm = {};
  $scope.myForm.Title = "";
  $scope.myForm.Content = "";
  $scope.CategoryId = {
    data: [{
        id: '316556404cac4a6bb47dd4c7ca2dac4a',
        name: 'name1'
    }, {
        id: '306e3d9a6265480d94d0d50e144435f9',
        name: 'name2'
    }]
  };       

 $scope.myForm.submitTheForm = function(item, event) {
 var dataObject = {
 Title : $scope.myForm.Title,
 Content : $scope.myForm.Content,
 CategoryId : $scope.CategoryId 

   };

   var responsePromise = $http.post("/url", dataObject, {});
   responsePromise.success(function(dataFromServer, status, headers, config) {
      console.log(dataFromServer.title);
   });
    responsePromise.error(function(data, status, headers, config) {
      alert("Submitting form failed!");
   });
 }
  });

Answer №1

To properly bind the categoryID to your array, ensure that your ngOptions expression correctly loops through the array. If not, you will need to bind the value of categoryId to a different model.

Start by creating a model for your categoryID:

$scope.formData.categoryId = null;

Then, make changes to your select markup:

<select ng-model="formData.categoryId" ng-options="item.id as item.name for item in CategoryData.list"></select>

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

Encountering the error message "Function.prototype.bind.apply(...) cannot be invoked as a constructor

I'm attempting to implement Controller Inheritance in AngularJS (1.6.9), but encountering an error in the console: Function.prototype.bind.apply(...) is not a constructor. Here's the snippet from the HTML file: <!-- Controller Inheritance --& ...

The issue with executing event.keyCode == 13 in Firefox remains unresolved

I've implemented a function that sends comments only when the "enter" key is pressed, but not when it's combined with the "shift" key: $(msg).keypress(function (e) { if (event.keyCode == 13 && event.shiftKey) { event.stopProp ...

Unable to generate StumbleUpon traffic for a URL through AJAX due to the API returning text/plain

I'm attempting to acquire StumbleUpon views for a specific URL using $.ajax. This is the API I am utilizing: http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://example.com/ Here is the complete code snippet: $.ajax({ type: "GET ...

Is it recommended to incorporate router.isReady when making requests with react-query?

Struggling with incorporating react-query into my codebase, currently using getStaticProps. Experimenting with router.isReady from next/router to ensure the page waits for router.query value before passing it as props to the react hook. Take a look at my ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...

OpenStreetMap not displaying on Android devices

I'm in the process of developing an application that focuses on displaying items on a map. My choice for the framework is ionic, built on top of Apache Cordova, and I've chosen OpenStreetMap as the mapping provider. While testing the app using Io ...

Retrieve a PDF file from an HTTP response using Axios

I'm currently working on a project that involves integrating Vue with a Laravel API as the back-end. One of the requirements is to be able to download PDF files from the server when a certain link is clicked. I am using axios for making GET requests, ...

Loading external libraries in Angular2: A step-by-step guide

I'm currently working on incorporating a Datepicker in Angular 2, but I'm facing an issue where the library is not loading. This is causing a template parsing error stating 'material-datepicker' is not a recognized element: My System.c ...

migrating information from one screen to another

So, I'm in the process of transmitting information from one page to another. Essentially, I retrieve data from an API and use that data to organize the page categories along with their respective details. Each detail acts as a link, and once clicked, ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Delaying http requests until cache is fully prepared without the need for constant checking

In a unique scenario I am facing, my http requests are caching intermediary results on the server. If the cache is not found, then another server is requested to build it. These requests are sent consecutively (in a loop) using AJAX to a Node Server, with ...

I'm building an angular website and considering using Ionic to develop the corresponding mobile apps. Can you recommend the simplest approach for this integration?

I have developed a responsive website using Angular 4 with Lumen serving as the Rest API. The website functions smoothly on both desktop and mobile browsers, but I now intend to venture into developing mobile applications. What would be the most straightf ...

I have encountered challenges trying to consume form data containing a zip file and several other parameters sent from an Angular 2 frontend in my Java backend

I keep encountering the issue with error code 415 Unsupported media type. My current process involves sending form data with a zipped file along with several other parameters. I have set the content type as multipart/form-data in Angular 2. On the Java ...

Upgrading email functionality: Combining PHP mail() with AJAX

My issue revolves around using the mail() function. When AJAX code is present, the email gets sent but without any message (the subject is intact though). However, when I remove the AJAX code, the email goes through without any problems. I'm not well ...

What is the best way to generate bootstrap rows from this code in React JS?

In my current array of objects, I have twelve items: { data:[ { type:"tweets", id:"1", attributes:{ user_name:"AKyleAlex", tweet:"<a href="https://twitter.com/Javi" target="_blank"> ...

Tips for creating a complex concatenation Grunt script that can identify matches across multiple directories

Looking to create a complex concatenation script using grunt. Check out my starting setup below: ___js |____dist | |____vents | | |____commonEvents.js | | |____compare.js |____libs |____src | |____events | | |____carousel.common.js | | |____compare.js | | ...

Conditional radio button disabling in Material-ui

Currently, I am developing a React application using material-ui. My goal is to disable all radio buttons within a RadioGroup when a specific event occurs, and then re-enable them once the event is no longer active. For example, when a button is clicked, ...

When the caret triangle is upside down, it indicates that a drop-down menu is available even when the

I am facing an issue with a dropdown list where the triangle indicator is incorrectly displayed: https://i.stack.imgur.com/L4NBW.png Both images show that the arrows are in reverse direction, and I am struggling to identify the cause of this problem. He ...

JavaScript - creating mathematical expressions without the need for operator overloading

In my JavaScript project, I am utilizing three.js and attempting to determine if a vector remains within a designated area as shown below: var THRESHOLD = 10; if (!is_in_rect(camera.position - forward * THRESHOLD)) // do something where camera.positi ...

What is the reason behind only receiving one-dimensional arrays?

var $arr = { field_hide : '', field_values: '', field_triggers: {} } function setTrigger ($trigger, $values, $show, $arr) { $arr.field_hide += $show + ','; $arr.field_values += $values + ...