setting a default value based on a condition in the ng-options

One straightforward question arises: How can I establish an initial value for my ng-options? The challenge lies in the requirement that the default value must be a specific one, which necessitates a conditional check to determine this particular value.

HTML

<select ng-model="selectedOption1" ng-options="horario for horario in dia.horarios" ng-change="vm.saveInitialSchedule($index, selectedOption1)">

Here is my JSON data:

https://i.sstatic.net/bkRkM.png

For each option, it's essential to verify if the option's value matches valorInicio. If a match is found, that value should be automatically chosen as the default one.

In the previous format, I used:

ng-selected="dia.valorInicio == horario" 

And it worked perfectly well.

However, since the 'ng-selected' feature is no longer available.

So, can anyone offer assistance?

Thank you!

//EDIT//

HTML

<ion-view view-title="Change Schedules">
<ion-content>
    <div class="list card" ng-repeat="dia in vm.dias">
        <div class="item item-divider" align="center">
            {{dia.nombre}}
        </div> 
        <div class="list">
            <label class="item item-input item-select">
                <div class="input-label">
                    First shift
                </div>
                <select ng-model="selectedOption1" ng-options="horario for horario in dia.horarios" ng-change="vm.saveInitialSchedule($index, selectedOption1)">
                </select>
            </label>
            <label class="item item-input item-select">
                <div class="input-label">
                    Last shift
                </div>
                <select>
                    <option ng-model="selectedOption2" ng-repeat="horario in dia.horarios" ng-change="vm.saveFinalSchedule($index, selectedOption2)" ng-selected="dia.valueEnd == horario" value="{{horario}}">{{horario}}</option>
                </select>
            </label>
        </div>
    </div>
    <div class="padding-horizontal"><button class="button button-block button-positive" ng-click="vm.saveSchedules()"> Save schedules </button></div>
</ion-content>
</ion-view>

Controller

(function() {
'use strict';

angular
    .module('example.changeSchedules')
    .controller('ChangeSchedulesController', ChangeSchedulesController);

ChangeSchedulesController.$inject = ['$state', '$scope', 'changeSchedulesService'];

function ChangeSchedulesController($state, $scope, changeSchedulesService ) {
    var vm = this;
    vm.state = false;
    vm.scheduleState = false;
    vm.days = [];
    vm.errorMessage = '';
    vm.loadSchedules = loadSchedules;
    vm.saveInitialSchedule = saveInitialSchedule;
    vm.saveFinalSchedule = saveFinalSchedule;
    vm.initialSchedules = [];
    vm.finalSchedules = [];


    initialize();

    function initialize() {
        loadSchedules();

    }

    function saveInitialSchedule(index){
        console.log("indexxxxxx:"+index);
        console.log("Option 1 : " + $scope.selectedOption1);
        debugger;

    }


    function loadSchedules() {
        vm.state = false;
        vm.scheduleState = false;
        changeSchedulesService.retrieveComplexSchedules()
            .then(function(days) {
                vm.days = days;
                displayChangeSchedules(true);
            })
            .catch(function(e){
                displayChangeSchedules(false);
                vm.errorMessage = e.concat(" Tap to reload.");
            });
    }

    function displayChangeSchedules(state){
        if(state == true){
            vm.state = true;
        }
        else{
            vm.state = false;
            vm.scheduleState = true;
        }
    }

    function saveInitialSchedule(index, time){
        vm.initialSchedules[index] = time;
        console.log(vm.initialSchedules);
    }

    function saveFinalSchedule(index, time){
        vm.finalSchedules[index] = time;
        console.log(vm.finalSchedules);
    }
}
})();

Answer №1

To assign the selectedOption1 to the initial selected horario, you can implement the following logic in the controller constructor:

if(conditionForInitSelectedObject == horarios[i]){
  $scope.selectedOption1 = horarios[i];        
}

Additional code snippet:

function loadSchedules() {
    vm.status = false;
    vm.changeScheduleStatus = false;
    scheduleChangeService.getSchedules()
        .then(function(days) {
            vm.days = days;

            for(var i = 0; i < days.schedule.length; i++){
               if(days.schedule[i] == day.initialValue){
                 $scope.selectedOption1 = days.schedule[i];
               }

               if(days.schedule[i] == day.endValue ){
                 $scope.selectedOption2 = days.schedule[i];
               }

            }

            showScheduleChange(true);
        })
        .catch(function(error){
            showScheduleChange(false);
            vm.errorMessage = error.concat(" Tap to reload.");
    });
}

Update 2

The data structure was not clear to me in my previous revisions, so the issue is how to initially select one option based on specific data.

Solution 1: You could utilize ng-selected when using ng-repeat with option tags

Solution 2: You could follow the approach mentioned earlier but adjust the HTML so that ngModel is not stored in static variables but rather:

<select ng-model="day.Selected" ng-options="schedule for schedule in day.schedules" ng-change="vm.saveInitialSchedule($index, selectedOption1)">

Ensure to initialize this when fetching data. This Plunker demonstrates the concept: https://plnkr.co/edit/UHasuk0RvYCS8omzlsg4?p=preview

Answer №2

After some trial and error, I finally figured it out! The key was setting the ng-model to the desired value or property from my JSON in order to display it by default.

Furthermore, whenever the user changes the option, Angular automatically updates the corresponding value in my JSON because it modifies the variable linked to the model.

select ng-model="dia.valorInicio" ng-options="horario for horario in dia.horarios" ng-change="vm.modifyStartHour($index, dia.valorInicio)"></select>

<select ng-model="dia.valorFin" ng-options="horario for horario in dia.horarios" ng-change="vm.modifyEndHour($index, dia.valorFin)"></select>

A big shoutout to @AndersVestergaard for guiding me towards the solution that ultimately helped me find the answer!

Cheers!

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

Using react hooks, I am refreshing the product image by replacing it with the thumbnail image

I'm currently working on an e-commerce platform that resembles Amazon. In the product detail page, I want the right side image to update when I click on a thumbnail image on the left side. The issue I'm facing is that upon first loading, the def ...

What is the best method for retrieving the entire row data based on the maximum value in a column?

function findMaxValue() { var highestValue = Math.max.apply(Math, $('.sira').map(function() { return $(this).text() })) alert(highestValue); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"& ...

Decoding the Language of HTTP Status Codes

Let's imagine a scenario where I create a file called api.js: const {somefunction} = require('../controllers/some-controller'); app.get('/data/', somefunction); In my some-controller.js: exports.somefunction = async (req, res,next ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

How to display (fade in a portion of an image) using .SVG

I have the following code in my DOM: <div class="icon-animated"><img src="icon_non_active.svg" id="icon_non_active"></div> There are two icons (.svg) available: icon_non_active & icon_active Can I animate the transformation from i ...

How come the instanceof operator returns false for a class when its constructor is present in its prototype chain?

While working on a NodeJS app, I encountered unexpected behavior when trying to verify that a value passed into a function is an instance of a specific Class. The issue arises when using instanceof between modules and checking the equality of the Class. e ...

moment js struggling with correctly interpreting the date format in a Japanese locale

I am having trouble translating the date format to Japanese locale as the output is incorrect. I have attempted to change the browser's locale settings, but it doesn't seem to be working in both Chrome and IE. app.filter('japan', funct ...

Firebase's push() method compared to Angularfire's $save() operation

When comparing angularfire .$save() to firebase .push(), what are the differences? I understand that push() generates a unique key when data is stored, but I'm having trouble replicating this behavior with angularfire. Should I stick to using .push() ...

Avoid mutating the prop directly and instead, utilize a data or computed property that is based on the value of the prop. The prop that is being mutated in this case is

Help me understand this issue that Vue is displaying, I am not sure what is going on. This is my progress element: <el-progress :percentage="percentCompleted" v-show="uploadingVideo"></el-progress> data() { return{ percentCompleted: 0 ...

Create a function that can dynamically assign properties to nested objects if they exist, essentially replicating the functionality of the _

I am trying to achieve the following result dynamically without manually specifying where the matches are located in the Object's properties. Intended Result const obj = { levelOne: { someFun: () => {}, levelTwo: { anArray: [], ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

What is the best way to superimpose an image onto a canvas?

I am working on a cool project where I have created a canvas that displays matrix binary code raining down. However, I would like to enhance it by adding an image overlay on top of the canvas. Here is my current setup: <div class="rain"> ...

What is the best method for sending variables to the `script.` block in Pug?

I am encountering an issue with the code in my index.pug file doctype html html head title= title body script(src=`${source}`) script. for (var event of events){ VClient.Event.subscribe(event, createDiv); } This is how ...

Tips for transferring information from Django to React without relying on a database

Currently, I am in the process of developing a dashboard application using Django and React. The data for the user is being pulled from the Dynamics CRM API. To accomplish this, I have implemented a Python function that retrieves all necessary informatio ...

Is there a method in Discord.JS to remove an embed from a message sent by a user?

Currently, I am developing a bot utilizing the Discord.JS API. This bot is designed to stream audio from specific YouTube links using ytdl-core. Whenever a link is typed in, an embed of the YouTube video appears. While there are methods to disable embeds o ...

The image zoom function is malfunctioning when trying to adjust the image position

Having some trouble with a code for image zoom in/out. When I adjust the position of the image by applying margin left to either the image or the image container (#view), it affects the zoom functionality - causing the image to move to the left during zoom ...

Disabling 'Input Number' feature is ineffective in Firefox browser

Is there a way to prevent the input value from changing when the up or down arrow is held, even if the input is disabled? I want to retain the arrows without allowing this behavior on Firefox. Give it a try: Press the up arrow. After 5 seconds, the input ...

Obtain the location coordinates from Google Maps API using an ajax() call

I am attempting to retrieve longitude and latitude coordinates from the Google Maps API using the following example: http://jsbin.com/inepo3/7/edit. I am expecting a 'success' popup, but I keep seeing the 'Error' popup. The Google Maps ...

Ways to activate auto completion without using a string

Can anyone assist us with the tinymce editor? We have implemented an auto completion feature using a plugin from TinyMCE's documentation, but we are having trouble changing the triggering behavior. Currently, it only suggests options when "@" is typed ...

It is not possible to submit a form within a Modal using React Semantic UI

I am working on creating a modal for submitting a form using React semantic UI. However, I am encountering an issue with the submit button not functioning correctly and the answers not being submitted to Google Form even though I have included action={GO ...