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

Simple Timer App with Vanilla JavaScript

Hey there! I am a newcomer to JavaScript and recently joined the stackoverflow community. Currently, I am working on a project called Pomodoro Timer with the goal of creating something similar to this example: http://codepen.io/GeoffStorbeck/full/RPbGxZ/ ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Tips for including subjects in JSON data

I am trying to include the subject in JSON data so that I can fetch it using $.each(data.subject). Below is my API code where I am retrieving all the data encoded in JSON format. Any assistance would be greatly appreciated. [{"id":"79","FirstName":"Elon", ...

Node.js is encountering an error with the post method where req.body is returning an empty

When utilizing cURL or Postman, the operations perform as anticipated curl -d 'username=Johny Sample&title=My First Post&description=We need some assistance cleaning up after the hurricane&postID=Johny Sample_1' http://localhost: ...

Animation effects compatible with iOS devices are professionally crafted using CSS

I just implemented a custom hamburger menu with animation using HTML, CSS, and JavaScript on my website. The animation works perfectly on Android devices but not on iOS. Any suggestions for fixing this issue? I attempted to add the Webkit prefix to each p ...

Spring Security does not support PUT requests with AngularJS and Spring Boot

Creating an Angular controller function $scope.updatePatient = function() { var patient = new patientUpdateService({id:"15", name:"m",lastname:"s"}); patient.$update(); } Defining an Angular service .factory("patientUpdateServic ...

Manipulate the <title> tag using jQuery or PHP

I have my own personal blog and I am trying to change the title tag dynamically when viewing different blog posts. My goal is to have the post title show up in the Twitter tweet button. I attempted the following methods: <script type="text/javascript"& ...

Is there a way in AngularJS to set all radio buttons to false when one is chosen as true?

When I retrieve true/false string values from the database, I am unable to alter the data. The example I provided is simply a representation of the string values true or false that I receive from the database. My goal is to have a single radio button disp ...

jQuery's AJAX feature fails to identify the newly modified div classes

For my new website, I am developing a simple checklist feature. To handle the check and uncheck requests from users, I'm using jQuery's $.ajax() function. Whenever a user clicks on the check or uncheck buttons, jQuery retrieves the validation tok ...

MySQL Entry Update Failure

This is the HTML/EJS code snippet: <div class="Edit-Panel" style="display: none;"> <div class="Edit-Wrapper"> <div class="Editing"> <p class="Edit-Header ...

Working with JSON data in Scala

After making a request to a REST service, I receive this JSON response. { "id": "6804", "signatories": [ { "id": "12125", "fields": [ { "type": "standard", "na ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

What is the best way to change CSS style for a button when clicked using JavaScript?

Is there a way to switch the background style of a CSS div when clicking the same button? function changeBg() { var divElem = document.getElementById("change-bg"); if (divElem.style.backgroundColor === "yellow") { divElem.style.backgroundColor ...

Retrieving online content and updating it upon reestablishing internet connection

Currently, I am in the process of developing an app that will feature a substantial amount of web content. My plan is to use Phone Gap build for its release; however, I intend to host all the content online and link to it from within the app. I have been c ...

Using Javascript to dynamically enable or disable an input field depending on the choice made in another field

I attempted to implement the solution provided in this answer for my code: How do I disable input field when certain select list value is picked but unfortunately, it is not working as expected. The scenario involves an HTML select field with the ID &apos ...

Utilizing JSON API authentication with Devise in Rails

Currently, I am working on an app using Devise and Rails to authenticate users from mobile devices. The issue arises when it comes to the sign up and sign in process, as users are sending their plain text passwords over the wire. I am wondering how I can ...

The backend response was "<Response [502]>" along with an error message stating that string indices must be integers

Currently, my goal is to initiate a REST request towards the specified end-point. import requests param1 = "abc" param2 = "def" input_data = """{{"param1": {}, "param2": {}}}""".format ...

What is the best way to display a unique modal on every tab?

I'm facing an issue where I am attempting to trigger a modal on each tab item, however the modal only opens on the initial tab. Clicking on any other item results in the modal opening on the first tab instead. Additionally, when I add new items, I am ...

Calculate the combined sum of values within dynamic inputs that share a common class, and automatically update the sum whenever input values are altered or new rows are added or removed dynamically

$("#add-btn").click(function() { $("#dynamic").append('<tr>' + '<td class="td">' + '<input type="number" name="Debit" class="form-control Debit"/>' + '</td>' + '<td c ...