Undefined value retained in $scope variable despite being assigned

I am facing an issue with a function in one of my Angular controllers.

Within the function, I check if a departure time has been provided. If it hasn't, I assign the current time to it in a HH:mm:ss format.

Even after assigning a value to $scope.selectedDepartureTime.departureTime, it still shows as undefined when I try to check its value. Why is this happening?

$scope.search = function () {
    if (!$scope.selectedDepartureTime.departureTime) {
        var time = new Date();

        var departureTime =
            ("0" + time.getHours()).slice(-2) + ":" +
            ("0" + time.getMinutes()).slice(-2) + ":" +
            ("0" + time.getSeconds()).slice(-2);

        console.log(departureTime);

        $scope.selectedDepartureTime.departureTime =
            departureTime;

        console.log($scope.selectedDepartureTime.departureTime);
    }

    $http({
        method: 'GET',
        url: '/train-times/journey?departureStation='
        + $scope.selectedDepartureStation.stationName
        + '&destinationStation='
        + $scope.selectedDestinationStation.stationName
        + '&queryTime='
        + $scope.selectedDepartureTime.departureTime,
        data: {}
    }).success(function (result) {
        $scope.journeyResult = result;
    });

    $http({
        method: 'GET',
        url: '/train-times/departure-times?departureStation='
        + $scope.selectedDepartureStation.stationName
        + '&queryTime='
        + $scope.selectedDepartureTime.departureTime,
        data: {}
    }).success(function (result) {
        $scope.otherDepartureTimes = result;
    });
}

The data is submitted through an HTML form:

<label for="departAfter">Depart After:</label>
<select id="departAfter"
   ng-model="selectedDepartureTime"
   ng-options="time.departureTime for time in departureTimes"
   ng-init="selectedDepartureTime='undefined'">
</select>

It seems like this should work and is a simple enough process.

Answer №1

Replace undefined with {}.

<label for="departAfter">Select departure time:</label>
<select id="departAfter"
   ng-model="selectedDepartureTime"
   ng-options="time.departureTime for time in departureTimes"
   ng-init="selectedDepartureTime={}"> <!-- Update undefined to {}-->
</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

Delaying Page Rendering in AngularJS Until $timeouts are Completed

Is there a method to delay AngularJS from rendering the next template until all $timeout functions have been executed? I am facing an issue where certain content is not displayed properly for a few milliseconds due to directives applying styles using $ti ...

Changing $scope does not automatically refresh the selected option when using ng-options with <select> in AngularJS

My select element is structured like this: <select ng-model="exportParam" ng-options="item as item.lib for item in allExportParams | orderBy:'lib'" class="form-control"> </select> To save its state for later display, I sto ...

Struggling to deserialize JSON information into a Dictionary with key and value pairs of strings

Looking to convert this JSON data into a Dictionary using native Javascript. var jsonData = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}"; However, encountering an error when trying to deserialize it with the following code: Diction ...

Navigating by Typing in the URL Bar in React

Whenever I paste a valid URL and press enter, the useEffect function in the parent component does not get triggered. However, if I reload the page, it works fine. Here is the code snippet: Routing path <Route path="/search" element={<Searc ...

Is it recommended for synchronous code invoked by a Promise's .then method to generate a fresh Promise

I recently wrote some code containing a mix of asynchronous and synchronous functions. Here's an example: function handleAsyncData() { asyncFunction() .then(syncTask) .catch(error); } After some research, I learned that the then method is ...

Increasing or setting a minimum value for a <input type="number"> compared to a specific number

I'm working with a form that looks like this: <input type="text" id="theName"> <input type="number" id="theNumber"> <input type="button" id="submitForm"> I need to implement validation using AngularJs when the submit button is clic ...

The checkbox's select all functionality is malfunctioning when employed with jquery

When the "select all" checkbox is clicked, it only selects the checkboxes on the particular page, instead of selecting all pages. This functionality is implemented using jQuery. The datatable contains hundreds of pages and data graph plotting is performe ...

Using incorrect string as JavaScript argument

Currently, I am facing an issue with passing parameters elegantly in my code. I have a link for deleting items which looks like this: <a href="javascript:confirmDelete('${result.headline}', ${result.id});"> The problem occurs when the res ...

Angular directives have unique scope behavior when working with the replace value

Looking for some guidance on a directive I have created with the following source code: var app = angular.module("myApp", ["mytemplate.html"]) var thai = angular.module("mytemplate.html", []).run(['$templateCache', function ($templateCa ...

Use jQuery to open and close HTML tags efficiently

It seems like the task I have at hand may not be as simple as I had hoped, so here I am seeking some reassurance. I am aiming to switch out an image with a closing div, then the image itself, followed by another opening div. Let me illustrate this with a ...

What is the best way to implement horizontal content scrolling when an arrow is tapped in mobile view?

I recently created a JS Fiddle that seems to be working fine on desktop, but in mobile view, the square boxes have horizontal scrolling. Here are the CSS codes I used for this particular issue: @media only screen and (max-width: 767px) { .product-all-con ...

Having trouble with gapi.client.request() not functioning properly?

I've been trying to use the Google API for freebase, and even though I'm following the correct call as per the documentation, it seems like there is an issue. The Chrome debugger is showing that something is wrong with this supposedly simple call ...

Navbar active class not updating on jQuery page scroll

My one-page website has a fixed navbar that I want to change its active status when scrolling down to specific div positions. Even though I tried using jQuery, the code doesn't seem to work as intended. Here is the snippet: // SMOOTH SCROLLING PAGES ...

Using Firebase Firestore to fetch an array field from a particular document and then leveraging those array values for mapping other documents

In my database, I have user and group collections. Each document in the user collection corresponds to a user UID and contains an array field called "userGroups" which lists the groups that user belongs to, with each group being identified by the group&apo ...

Utilizing Q for Node.js promise handling

I am currently working on a Node application where I need to utilize promises for handling asynchronous calls. Although I have a foreach loop inside a .then(function()) of a promise, I am facing an issue where I am unable to return the final result of the ...

Utilize local JSON file to display images on a webpage using AngularJS

Where am I making a mistake? I am trying to display images from a datahl.json file on my web page, but for some reason, I am unable to access them. Please review the code snippets below and help me out. If possible, provide a solution using Plunker edito ...

Sift through JavaScript problems

My goal is to implement a filtering function on my input that will display a different result. However, I have encountered an issue where the this.data.stationInfo.stations array is being changed, as shown in the console.log output. According to the Mozil ...

Assistance needed to make a jQuery carousel automatically rotate infinitely. Having trouble making the carousel loop continuously instead of rewinding

Currently, I am in the process of creating an auto-rotating image carousel using jQuery. My goal is to make the images rotate infinitely instead of rewinding back to the first image once the last one is reached. As a beginner in the world of jQuery, I&apos ...

What is the best way to notify a user one minute before their cookie expires using PHP and JavaScript?

I need a solution to alert my logged-in users one minute before their cookie expires, allowing them to save content in the CMS. Any ideas on how I can make this happen? In my auth file, I have configured the following: setcookie("USERNAME", $user,time()+ ...

How to effectively secure disabled or read-only input fields from JavaScript?

I am currently working on creating an HTML/PHP page that includes three hidden input fields. These fields are pre-set with values by the server and have the disabled attribute applied to them. The purpose of these hidden fields is to store information on o ...