Tips for creating a function to capture dropdown list change eventsHere are some steps

Within my html file, I have the following code snippet:

<select ng-model="selectedCar" ng-change="changedValue(selectedCar)" ng-options="x.license for x in fhu.carList" >
        <option value="">Select Car</option>
</select>

I am unsure of how and where to incorporate the changedValue function within my controller. Being new to Angular and JavaScript, a concrete example would be greatly appreciated. The controller is provided below and the dropdown list population is functioning correctly... almost. However, the focus at this moment is on implementing the selection change function.

(function() {
    var app = angular.module("fhu", []);

    app.controller("FhuController", function(){

        this.carList = cars;

    });


    $(document).ready(function(){

        var car = {};

        $.getJSON("fillingapi.php?action=get_cars",function(data){
             var i=0;
             for(i=0;i<data.length;i++){

                cars.push( {license: data[i].license, descr: data[i].descr});               

            }
        });
    });

    var cars=[];

    })();

Answer №1

Regarding the placement of changedValue inside your controller, it is already being handled by ng-model="selectedCar". Angular will automatically update this value for you, allowing you to access the selected car from the drop-down menu in your controller using $scope.selectedCar.

A few additional points to note:

  • Avoid mixing Angular and jQuery unnecessarily, as they have different methods for manipulating the view.

  • Angular features two-way binding, eliminating the need to manually listen for document ready events like in jQuery. Angular handles scope and view updates automatically.

  • Using 'this' in AngularJS can lead to scope issues; opt for $scope instead.

  • Instead of using $.getJSON from jQuery, consider utilizing Angular's $http component for data retrieval.

I have created a functioning example on Plunker: https://plnkr.co/edit/1xqvFVTed9I7lJj9NkFH?p=preview


var app = angular.module('fhu', []);

app.controller('FhuController', function($scope, CarService) {
    $scope.selectedCar;

    CarService.getCars().then(function(listOfCars) {
      console.log(listOfCars);
      $scope.carList = listOfCars;
    });

    $scope.changedValue = function() {
      alert('You just selected '+ $scope.selectedCar.licence);
    }              
});

app.factory('CarService', function($http) {

  const getCars = function() {
    return $http.get('https://www.rantakallio.fi/fillherup/fillingapi.php?action=get_cars');
  };

  return { getCars };
});

Analysis of the code:

  1. I removed unnecessary function wrapping.
  2. Eliminated the use of jquery document.ready.
  3. Replaced jquery $.getJson with Angular's $http component for consistency.
  4. Introduced a service for HTTP requests to be injected across controllers if needed.

The line CarService.getCars() calls a function named getCars within a factory called CarService, which returns a promise for asynchronous handling (using $http). The promise is unwrapped in the controller to update the carList variable, triggering automatic view updates by Angular. Similarly, selecting an option triggers model updates in the controller without passing the value explicitly into the function.

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 is the best way to retrieve a username by using a checked checkbox in JavaScript or jQuery?

i HTML <div id="notApprovedUsers"> </div><button onclick="approveUsers()">Approve</button> </div> i enjoy working with checked users passed in the userList parameter. ...

Can you explain the purpose of the `Sizzle.tokenize` function?

The mysterious function <code>Sizzle.tokenize lacks documentation and comments in the source code. What exactly is its purpose? Explore the code ...

Unable to retrieve a response, the operation `users.findOne()` has exceeded the buffering time limit of 10000ms

I encountered an issue when attempting to make a POST login request. The frontend is deployed on Netlify here, and the backend is deployed on Heroku here. Here are my backend logs . I am receiving `users.findOne()` buffering timed out after 10000ms in ...

"One way to embed a YouTube video player in a webpage is by replacing the YouTube link with an iframe YouTube video player,

As the administrator of a forum, I am looking for a way to automatically convert any YouTube video links posted by users into embedded iframe players on my ASP.NET+C# platform. Is there a method to replace this Link http://youtu.be/uN-A8eHte1g with < ...

Testing the API client against a remote API with constantly changing endpoints

Imagine I'm developing an API client for a complex API that is constantly changing and unreliable. I want to test this client using Jest, but I prefer to test it against a snapshot of the API response rather than the live API. However, I don't wa ...

My angularjs app hosted on Heroku is experiencing difficulty caching S3 images in the browser, despite setting cache-control headers

I am currently facing an issue with enabling browser caching for S3 images. My AngularJS app is deployed on Heroku and utilizes images stored in an S3 bucket. Despite my efforts, the browser does not cache the images as intended. Instead, it repeatedly req ...

Utilizing JavaScript to control the visibility of a div based on radio button selection without the need

I am facing an issue with my HTML code that is only partially working. I am attempting to display text inputs based on a radio button selection. At the moment, the code successfully hides the other options when a radio button is clicked, but upon the ini ...

Selenium does not support running Javascript code

I am currently utilizing capybara in conjunction with Selenium as the driver. I am facing an issue where clicking on an element does not trigger the associated javascript to reveal a specific div. Below is my code snippet: scenario 'currently used t ...

What are the steps to designing your own unique custom button with Material-UI?

While Material-UI allows you to utilize withStyles() for creating a Button with a predefined set of styles, I am curious if it is achievable to achieve the same result using props instead. This would ensure that all custom buttons I create automatically ha ...

What steps can be taken to address the issue of "Failed to compile"?

import React, { useEffect } from 'react' import { Row, Col, List } from 'antd' import Axios from 'axios' import { useState } from 'react' import SideVideo from './Sections/SideVideo' import Subscribe from & ...

I need to make a GET request via Ajax to reach out to express, but unfortunately, the request is not being received by express

Below is the code that I have written. This is the back end code (express) router.get('/principal/leave/approval/:id',function(req,res){ console.log('requested'); var approval; if(req.body.approve){ approval=true; }else{ a ...

Utilizing Props in Vue.js to Access Data for v-model

After browsing online, I attempted to pass props to data in the following manner: Child Component: props: { idInput: { type: String, required: false }, nameInput: { type: String, required: false }, }, data() { return { id: this.idInput, na ...

Efficiently Incorporating JavaScript Variables into DataTable's aoData

I am facing an issue with a variable named search_gen, which is generated through an ajax request (shown below). var search_gen; $.ajax({ type: "POST", url: link+module_name+'search_generator/'+module_active, dataType: "text", as ...

After installing the latest version of [email protected], I encountered an error stating "Module 'webpack/lib/node/NodeTemplatePlugin' cannot be found."

Upon updating to nextjs version 10.1.3, I encountered an error when running yarn dev. Error - ./public/static/style.scss Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin' Require stack: - /path_to/node_modules/mini-css-extract-plugi ...

Default value not chosen in PHP dropdown

Here is my PHP code snippet: <?php require_once('../Connections/baglanti.php'); $settings = $db -> prepare("SELECT * FROM mestan_settings"); $settings-> execute(array()); $settingswrite = $settings->fetchAll(); foreach($sett ...

Retrieving information through a jQuery ajax call

I've been working on creating an AJAX filter for a car list, but I've hit a roadblock in the final stage. My setup involves two files: index.php and filter.php. Within index.php, I have a form with dropdown lists and sliders. Here's the cod ...

Can PHP Webpage Make an AJAX POST Request to Express Server on the Same or Different Ports?

Trying to enable a POST request through AJAX from a site to an express server triggered some unexpected challenges. When running the server on the same localhost port as the website (localhost:8080), the webpage fails to render and an error message pops up ...

Displaying various dropdown content when different buttons are clicked

In my interface, I have implemented a drop-down menu that consists of two options. When the "Add Equipment" option is clicked, everything functions properly as expected. However, when I select the "Deployed Equipments" option, the drop-down for "Add Equipm ...

Troubleshooting incompatibility issues between Tailwindcss and NextJS 12 due to experimental features

When I first started using NextJS 12, I decided to try building a project with tailwind. This is my package.json file: { "name": "test", "version": "0.1.0", "private": true, "scripts": { ...

Issue with the _.filter function in lodash library when used in a Node.js environment

My goal is to remove rows from a CSV file that already contain email addresses found in Mailchimp. Although I attempted to achieve this with a function, it seems that the number of elements returned is not accurate: async function testDeleteEmails(listID, ...