ng-model not initializing first select choices in ng-options

My select element is not initializing with the desired value, despite my efforts. The init value seems to be failing.

HTML

<select class="select-form-control"
    ng-model="lossGainProb"
    ng-options="item.display for item in possibility track by item.value" 
    ng-init="EventDetails.lossGainProb">

JavaScript

$scope.possibility = [{
    display: '0%',
    value: 0
}, {
    display: '5%',
    value: 5
}];

$scope.EventDetails.lossGainProb = 5;

Answer №1

After analyzing the provided code snippet, I managed to craft a functional demo that showcases its capabilities. You can check it out here

<div ng-app="myApp" ng-controller="myCtrl">
<select class="select-form-control" ng-model="lossGainProb"
  ng-options="item.value as item.display for item in possibility">
</select>
</div>

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
       $scope.possibility =[ {
            display : '0%',
            value : 0
        }, {
            display : '5%',
            value : 5
        }];

    $scope.lossGainProb = $scope.possibility[1].value;

});

Answer №2

To properly integrate the item being tracked into the Angular list, follow these steps:

$scope.options = [{
    display: '20%',
    value: 20
}, {
    display: '30%',
    value: 30
}];

$scope.EventDetails.gainLossProb = $scope.options.filter(function(item){ return item.value === 30})[0];

Check out the running example on Codepen http://codepen.io/jsmith/pen/rpbNop

Answer №3

Upon review, I have identified two errors:

  1. The incorrect use of ngInit. It does not define the initial binding for the ngModel directive; rather, it is an expression evaluated against the scope after initialization. To establish initial model bindings, consider using something like

    <select ng-init="lossGainProb = EventDetails.lossGainProb"></select>
    

    An alternative (and preferable) method would be to define this in your controller directly, such as

    $scope.lossGainProb = $scope.EventDetails.lossGainProb;
    
  2. Your ngModel is linked with the entire "possibility" object instead of solely the value property. Assuming you only want the value to serve as your model value, adjust the ngOptions as follows

    <select ng-options="item.value as item.display for item in possibility"></select>
    

    This specifies that ngModel should correspond with item.value, while utilizing item.display as the label.

Incorporating these corrections, your select element should appear similar to

<select class="select-form-control"
    ng-model="lossGainProb"
    ng-options="item.value as item.display for item in possibility"
    ng-init="lossGainProb = EventDetails.lossGainProb">
</select>

For a functional demonstration, refer to this working Plunker.

Answer №4

One way to avoid using ng-init is by initializing in the controller like this:

$scope.initialValue = {};
$scope.initialValue.amount = 10; 

Avoiding the use of ng-init is recommended - see more information here: https://docs.angularjs.org/api/ng/directive/ngInit.

Answer №5

Here is another way to tackle the problem:

<select class="custom-select" ng-init="currentProb = chance[1].value" ng-model="currentProb" ng-options="item.value as item.display for item in chance"> </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

Unable to trigger JQuery .blur event

I am currently working on implementing server-side validation for an input field that needs to be validated when it loses focus. However, I'm running into an issue where the alert is not triggered when the input field loses focus. Here's a snipp ...

Having issues with 'direction' in React withStyles causing errors

I am experiencing an issue with my React website where I am using the withStyles feature to apply styles to a material-ui Grid element. Specifically, when attempting to use direction: "column" in the style, I encounter the error message provided below. Th ...

How to Implement Snap-Enabled Dragging in a Container Using jQuery UI

Issue Description (Fiddle): I am using the jQuery UI's .draggable() function to make the red element snap inside the blue container. However, it is snapping to one edge only instead of completely fitting inside (both edges). It requires further dragg ...

Unable to display Apexcharts bar chart in Vue.js application

Struggling to incorporate Apexcharts into my Vue.js site, but unfortunately, the chart isn't appearing as expected. -For more guidance on Apexcharts, check out their documentation Here HTML <div class="section sec2"> <div id="chart" ...

Unable to Define Headers in Fetch GET Call

My current struggle involves sending a GET Request from the browser to my backend (which uses node + express). However, I am encountering issues with setting the headers properly. Below is the code snippet from the frontend: let accessToken = localStorage ...

arrange the elements in a specified sequence

I am trying to sort an array in a specific order var customOrder = { "1st Presentation / Meeting": 0, "Follow-On Meetings": 1, "Hold\/Uncategorized": 2, "MGL": 3, "PGL": 4, "BGL": 5, "RGL": 6, "SGL": 7, "Uncategorized Leads": 8, ...

Retrieve the titles of all WordPress posts

I implemented a feature in my Wordpress blog that suggests search results using this code snippet. However, the current setup searches through all tags and I would like it to only search post titles. Any advice on how to achieve this would be greatly appr ...

How do I retrieve distinct values from Math.random in JavaScript and prevent them from repeating?

I am attempting to fetch HTML dom elements remotely from a website using jquery/javascript. These elements are stored in an array and are unique, however, when I attempt to display them by generating random indexes with math.random() * my array.length, I n ...

Utilizing Grails Tag Libraries to Retrieve an Element's Value

I have my own TagLib with a custom tag named boxLink that generates a Remote Link and opens a Modal: Closure boxLink = { attrs, body -> Integer modalId = OwnUtil.getRandomNumber(1000) Map params = attrs.params ? attrs.params : [:] ...

Encountering an issue with the factory test within the controller, as it indicates that

Seeking assistance with testing the function below within a controller. getEmployeeList is a function within the controller that loads data in the UI upon controller initialization. It relies on a factory, but after implementing the code snippet below in ...

What is the process for obtaining real estate listings through the 3taps API?

Looking to extract real estate listings specifically from the 3taps API. offers listings across various categories, but my focus is on extracting only those in the Real Estate Category. My development work will be in Microsoft .Net, leaving me with just ...

What is the best way to observe objects in Vue.js?

I have an object containing longitude and latitude coordinates? data(){ return{ center2:{lat:0,lng:0} } } I am attempting to watch these values but it's not working as expected watch:{ "center2.lat":function (newValue, oldValue) { ...

When refreshing the webpage, it becomes glitchy but then corrects itself

Currently working on a website, I've encountered a frustrating problem that has me scratching my head. This issue occurs across multiple pages; upon refreshing the page, the navbar, search bar, and other elements become completely disorganized. Stra ...

Hide the off-canvas menu when clicking outside

I recently created a unique "slide-out" menu which you can check out here: SASS Slide-out Menu. While it is functional, I am looking to add a feature where clicking outside of the menu will automatically close it by removing the "nav-open" class. I a ...

What is the best approach for retrieving the value of a deeply nested JSON object?

Currently, I am developing an application in JavaScript and I have encountered a JSON object. Here is a simplified version of the JSON object: { "data": [ "user": { "pictures"{ "sizes"[ 0: { "link": "http://www" ...

JavaScript: Navigating Through Frames and iFrames in Internet Explorer

Is there a way to run JavaScript code after my iFrames or Frames have finished loading? It seems like document.onReady fires before the frames are actually displayed on the page. Any ideas on how to make this work? I came across a plugin called FrameReady ...

Is it possible to omit a specific file from a GET request when utilizing angular?

As a newcomer to the world of Angular, I embarked on a project to deepen my understanding. My goal is to utilize a Pokemon API to display sprites that correspond with their respective names. However, I've encountered an issue where certain numbers in ...

What is the best way to retrieve route data based on route name in VueJs?

When working with VueJs, I have found that I can easily access the data of the current route. However, I have encountered a situation where I need to access the data of a different route by its name. Let's say I have defined the following routes: [ ...

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

Unable to access a file located in the views folder through the Express route

I'm new to programming and struggling with getting the recipe.ejs file to display. I can't seem to create a proper route from recipe.js to render the file. Any assistance would be greatly appreciated. /routes/recipe.js var express = require( ...