AngularJS - Choose and establish initial values for Editing or Creating New Items

My first project involving AngularJS has left me a bit stuck when it comes to using the select list. I need to either set the default value to the first option for a new entry, or if it's an edit, select the appropriate value.

In my form, there are two select lists and I suspect that my ng-options tag might be incorrect.

invite.tpl.html

<select ng-model="selectedUser" ng-options="user.id as user.user_name for user in users"></select>
<select ng-model="selectedEvent" ng-options="event.id as event.name for event in events"></select>

The controller responsible for fetching/posting JSON data.

invite.js

.controller('InviteCtrl', function InviteController( $scope, InviteRes, $state, $stateParams ) {
  $scope.inviteId = parseInt($stateParams.inviteId, 10);
  $scope.users = InviteRes.Users.query();
  $scope.events = InviteRes.Events.query();

  //EDIT (HAVE ID) - SET SELECTS TO THE USER/EVENT 
  if ($scope.inviteId) {
    $scope.invite = InviteRes.Invites.get({id: $scope.inviteId});
    $scope.selectedUser = $scope.invite.user_id;
    $scope.selectedEvent = $scope.invite.event_id;
  }
  //NEW (NO ID) - SET DEFAULT OPTIONS TO FIRST USER/EVENT
  else {
    $scope.selectedUser = $scope.users[0];
    $scope.selectedEvent = $scope.events[0];
    $scope.invite = new InviteRes.Invites();
  }

Function for saving the data.

$scope.submit = function() {
    $scope.invite.user_id = $scope.selectedUser;
    $scope.invite.event_id = $scope.selectedEvent;
    //IF ID - UPDATE ELSE NEW
    if ($scope.inviteId) {
      $scope.invite.$update(function(response) {
        $state.transitionTo('invites');
      }, function(error) {
        $scope.error = error.data;
      });
    }
    else {
      $scope.invite.$save(function(response) {
        $state.transitionTo('invites');
      }, function(error) {
        $scope.error = error.data;
      });
    }
  };

Defining resources to fetch data from.

.factory( 'InviteRes', function ( $resource )  {
  return {
    Invites: $resource("../invites/:id.json", {id:'@id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
    Users: $resource('../users.json'),
    Events: $resource('../events.json'),
  };
})

I've tried various solutions found in articles, but I'm still facing issues with setting values and saving the form correctly.

Answer №1

If you're working with the resource API, keep in mind that it may not return results immediately according to the documentation:

Remember that when you call a method on a $resource object, it may initially return an empty reference

Before assigning values, make sure they are available first. You can adjust your code like this:

if ($scope.inviteId) {
    $scope.invite = InviteRes.Invites.get({id: $scope.inviteId}, function() {
        $scope.selectedUser = $scope.invite.user_id;
        $scope.selectedEvent = $scope.invite.event_id;
    });
}

When using the select directive, it's recommended to use objects instead of values, for example:

<select ng-model="selectedUser" ng-options="user.user_name for user in users"></select>
// in controller:
$scope.selectedUser = $scope.users[1];

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

Stop the default drag behavior on an input range element in VueJS

Is there a way to disable the default drag functionality of an input range element without affecting the click feature? Users should be able to change values by clicking instead of dragging. <input type="range" min="0" max=& ...

Unable to send data using GET method after implementing passportjs integration

In the route.js file, I have implemented the following REST method: app.get('/api/todos', isAuthenticated, function(req, res) { DB.TodoTable.find() .exec(function(err, todos) { res.json(todos, function(err){ if (err) ...

Is there a way to directly display all the content in pagination format without a print preview option?

I have been tasked with implementing a feature that involves displaying content using pagination and allowing users to print all the content at once with a single click on a print button. However, I am currently experiencing an issue where clicking the pri ...

Saved as a list in serialized form, with only a single record stored

I managed to retrieve a list containing an example of 1 ID: 12 History and stored it in the Customer model for mapping, placing it under customerList to consolidate it. However, when I attempted to serialize it, the output appeared as follows. If the cust ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Angular directive causing issue with IE input element focus functionality

I am facing an issue where the focus is not being set on the first input field in a dynamically populated div when using Internet Explorer, although it works fine on Chrome. You can check out the plnkr example here. The focus setting is implemented within ...

Ensure that the URL is updated correctly as the client navigates between pages within a Single Page Application

Seeking a solution for maintaining the URL in a Single Page application as the client navigates between pages, with the URL changing in the background. I attempted using @routeProvider but it doesn't seem to be suitable for my situation. Any suggestio ...

Failed to fully install all dependencies for my project with yarn install

After cloning a project from gitlab, I attempted to install the dependencies using the yarn install command. However, there are several dependencies that yarn is unable to install and it keeps showing the error message: info There appears to be trouble wit ...

Guide on sending a personalized email to multiple recipients using office.js

Is it possible to send individual emails when using office.js in Outlook for mail delivery? For instance, if there are 5 recipients, can the email be sent so that each recipient only sees their own email and not others'? This is unrelated to BCC fun ...

Interpret data from an external JSON file into a HighCharts chart using JavaScript

Currently, I am exploring the process of incorporating HighCharts Chart data directly within the actual webpage. Below is the complete code snippet: <!DOCTYPE html> <html><head> <script type="text/javascript" src="http://code.jquery. ...

Is it secure to utilize the Firebase secret within Angular JS for administering updates?

My goal is to set up a user on Firebase, create a user profile, and assign the level property as 5. I want to ensure that no one, not even the user themselves, can alter the level property to a different number. Only an admin should have permission to do s ...

What strategies can be employed to tackle the challenges posed by Ajax asynchronous calls?

Beginner in JavaScript - I just wanted to mention that upfront. Take a look at this straightforward example where I aim to create X number of gauges, with the value of X being retrieved from JSON using an Ajax call. <body> <div id="gServer"> ...

Combining JSON files effectively with Python

I have limited experience with JSON and have never used Python packages to manipulate JSON files. I currently have 10 JSON files that I need to combine into one using Python. All 10 files have the exact same structure, each containing approximately 50,000 ...

Using jQuery to access the value of the CSS property "margin-left"

I created a JavaScript game with moving divs that have different transition times. The game includes a function that is called every 1/100 seconds, which checks the position of the divs using: $("class1").css("margin-left") Here's the strange part: ...

What are some strategies for managing two APIs in a single UIViewController?

I have a single ViewController containing an UIImage and two UITextFields, along with one UITableView. The data to populate these UI elements is fetched from an API. The first API provides the data for the UIImage and UITextFields, while the second API fe ...

Adding a stylesheet dynamically to the <head> tag using $routeProvider in AngularJS

Is there a way to load a specific CSS file only when a user visits the contact.html view on my AngularJS application or site? I came across this helpful answer that almost made sense to me How to include view/partial specific styling in AngularJS. The acce ...

Creating a button in ReactJS with text displayed under an icon

Presently, I am working with a component that looks like this: https://i.stack.imgur.com/qGCwj.png This is the code for the component: import React from "react"; import {withStyles} from "material-ui/styles"; import Settings from "material-ui-icons/Setti ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

Script on the server side fails to execute following validation of form

Hey there, I'm struggling with my signup form. I want to submit the form using ajax after completing validation. I've used a jQuery plugin for validation, but whenever I click on any field, the ajax request is automatically sent to the server and ...

Managing errors that occur while handling JSON with AJAX by implementing a suitable backup plan

Imagine there is a user.json file stored on a web server that contains: { "name” : “ivana”, “age” : “27” } Now, I make a request to retrieve this JSON data using the following code: var user = $.ajax({ url: pathsample.com/user.js ...