Choosing the selected option in AngularJS

I am facing a frustrating issue with understanding how AngularJS manages select option values and selections. I have a basic item that I pass to a modal window, which includes a template_id. Additionally, I have a list of templates with names and ids, and I want to create a select field where the option with the value matching the item's template_id is automatically selected:

<select name="templateId">
  <option value="8000">name</option>
  <option value="8001" selected>name 2</option>
</select>

To achieve this with AngularJS, I use the following code:

<select name="templateId"
    ng-model="domain.templateId"
    ng-options="t.template_id as t.name for t 
                in templates track by t.template_id">
      <option value="">Choose template</option>
 </select>

In the controller, I set the 'selected' value as follows:

Data.get('templates').then(function(result) {
    $scope.templates = result;
});

$scope.domain = {
    template_id: item.template_id,
    templateId: { template_id: item.template_id }
};

While I can successfully send the template_id to the REST API, the response indicates:

template_id: 8000

However, there is a minor issue with the select element. Initially, the correct item is selected, but if I try to choose another option, it reverts back to the default 'Choose template' option, even though the actual selected item remains the one set in the controller. This behavior is not what I intend. Once this initial issue is bypassed, the select field functions correctly. How can I fix this inconsistency?

Answer №1

Below is a sample solution to address your problem.

angular.module('app.select', [])
  .controller('SelecetCtrl', function($scope) {
    $scope.templates = [{
      template_id: 1,
      name: 'tst1'
    }, {
      template_id: 2,
      name: 'tst2'
    }, {
      template_id: 3,
      name: 'tst3'
    }];

    $scope.selected = {
      template: {
        template_id: 2
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app.select'>
  <div ng-controller='SelecetCtrl'>
    <select name="templateId" ng-model="selected.template" 
            ng-options="t as t.name for t 
                in templates track by t.template_id">
      <option value="">Choose template</option>
    </select> 
  </div>
</div>

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 could be causing the visibility issue with my navigation items in the bootstrap navigation bar?

Currently, I am experiencing a puzzling issue with the navigation bar on my live website. The navigation items seem to flicker for a brief moment and then disappear entirely. This unexpected behavior is certainly causing me some concern. I crafted the us ...

Error: Attempting to access the 'HotelInfo' property of an undefined variable led to an uncaught TypeError

//initiating an AJAX request to access the API jQuery(document).ready(function() { jQuery.ajax({ url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&a ...

Can we safely save a value in session storage directly from the main.js file in Vue?

Throughout the user session managed by Vuex, I have a session storage value set to false that needs to be monitored. Setting up this value directly from the main.js file looks like this: import { createApp } from 'vue'; import App from './Ap ...

Unable to transmit information back to React

Recently stepping into the world of React and Node.js, I have successfully created a function in my Node.js application that executes a Python script using child process. However, I seem to be facing a challenge with my router post method named pythonExecu ...

Difficulty: Issue with displaying Backbone collection using Mustache template

I'm new to backbone js and Mustache. I want to load a backbone collection on page load from rails json object to avoid making an extra call. However, I'm facing issues when trying to render the backbone collection using a mustache template. Here ...

What could be causing my checkbox to become unresponsive and fail to reset?

I recently created a function to update my page title when the toggle button is clicked, but unfortunately, it seems to be getting stuck after the click. I can't seem to pinpoint the issue with this function, as I've tried coding it in both JQuer ...

Testing the $save() function of $resource in Angular can be done through a series of

I am currently working on a service that utilizes $resource() to make POST requests in my controller using $save(). I am encountering difficulties while attempting to write Jasmine tests for the SettingAdd() Controller. The issue lies in setting up the cor ...

Failed to create WASM module: "module does not exist as an object or function"

I'm attempting to initialize a .wasm file locally within node.js in order to execute the binary on my local machine and mimic the functionalities of a webpage. Below is a simplified version of my setup: const fetch = require("node-fetch"); const impo ...

Can you suggest a more efficient method for retrieving data from a string?

Imagine having an array of strings with various information, and you need to extract specific details from them. Is there a simpler method to achieve this task? Consider the following array: let infoArr = [ "1 Ben Howard 12/16/1988 apple", "2 James S ...

Methods for dynamically adjusting content based on window width in Three.js

Currently, I have implemented a basic window resizing code in my project: function onWindowResize() { windowHalfX = window.innerWidth / 2; windowHalfY = window.innerHeight / 2; camera.aspect = window.innerWidth / window.innerHeight; came ...

Combining meshes results in a lower frame rate

I have combined approximately 2500 meshes, each with its own color set, but my FPS is lower than if I had not merged them. Based on THIS article, merging is recommended to improve FPS performance. Is there something I am overlooking? var materials = new ...

Node.js and socket.io come together in this collaborative text editing tool

I'm currently working on a collaborative app utilizing node and sockets that includes a simple text tool feature. My goal is for any user who types and applies text to the canvas to have that text visible to all other connected users. Here's wha ...

What is causing this code to break when using ajax's `data` parameter?

I'm relatively new to JavaScript, and I've been working on some code that seems to be properly formatted. However, whenever I add the data elements, it breaks the code. I've checked the jQuery documentation and as far as I can tell, I'm ...

How to pass the ng-repeat $index value as a parameter in AngularJS

Within the code snippet provided, there is a shell page index.html and a partial view currently utilized by two different controllers. The static data in AppController is connected to the list.html partial view and displayed as a table. In the JavaScript p ...

How to display a modal within a router-link in Vue 3?

Below are buttons with router-links. However, I only want the calculator button to open a modal. When I execute the code provided, all buttons trigger the modal instead of just the calculator button. Output: https://i.sstatic.net/layQ1.png Router-link C ...

Styling Your HTML Background with CSS and Enhancing it with JavaScript

I am lost when it comes to understanding the design of I have spent hours researching how to create backgrounds using shapes and css, but I haven't been successful. Can someone please help me figure out how to create a background similar to . Thank ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

The server response value is not appearing in Angular 5

It appears that my client is unable to capture the response data from the server and display it. Below is the code for my component: export class MyComponent implements OnInit { data: string; constructor(private myService: MyService) {} ngOnInit ...

What is the process for cancelling a pending request using jQuery in JavaScript Selenium?

My website has a high volume of users clicking on one button. Waiting for long-pending ajax requests to get responses, sometimes over a minute, seems nonsensical. I understand how to wait for the response, but how can I cancel it? How do I cancel all pend ...