Sending an Angular expression based on an identifier

When the onchange() event is triggered in the Select/Option element, it is supposed to write the value of the JSON file as an angular expression to the test ID div.

However, it currently writes it as a string: {{names[1].thnev}} (Manually inserting this into the ID div works fine.)

I have been struggling with this for the past 4 hours. Can someone please help me figure out what I missed?

<div ng-app="myApp" ng-controller="customersCtrl">      
    <select id="thaz" name="thaz" class="selectbox" onchange="onChange(this.value)">
        <option ng-repeat="x in names" value="{{x.id}}">{{x.id}} - {{x.thnev}}</option>
    </select>

    <div id="list"></div>

</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
        $http.get("al_list_th.php")
        .then(function (response) {$scope.names = response.data.records;});
    });

    function onChange(value) {
        document.getElementById("list").innerHTML = "{{names[" + value + "].thnev}}";   
    }
</script>

Answer №1

One way to simplify the issue is by utilizing the pre-existing functionalities within AngularJS.

For this particular scenario, we can employ ngModel to link the value of the select with a variable in our template, which we will name as selectVal.

Subsequently, we can directly include {{names[selectVal].thnev}} within the designated div where the desired output should be displayed.

To demonstrate these adjustments, I have compiled an illustrative example:

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

app.controller('customersCtrl', function($scope, $http) {

  $scope.selectVal = "default";
  $scope.names = [{id: 0, thnev: 5}, {id: 1, thnev: 6} ];

  //$http.get("al_list_th.php")
    //.then(function (response) {$scope.names = response.data.records;});
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>

<div ng-app="myApp" ng-controller="customersCtrl"> 
     
    <select id="thaz" name="thaz" class="selectbox" ng-model="selectVal">
        <option value="default">None</option>
        <option ng-repeat="x in names" value="{{x.id}}">{{x.id}} - {{x.thnev}}</option>
    </select>

    <div id="list">
    {{names[selectVal].thnev}}
    </div>

</div>

Note: In my code, I included an additional option for a default selection instead of leaving the dropdown initially blank. This step is optional -- the code will function similarly without it.

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

The requested resource is missing the 'Access-Control-Allow-Origin' header, resulting in an error message

When trying to retrieve a JSON file from Instagram, I encountered an issue while using $http.get : insta.ctrl : insta.controler 'instaCtrl' ($scope, $http), -> $http.get('http://api.instagram.com/publicapi/oembed/?url=http://instagr. ...

Steps to show a Google Maps marker with the help of ajax

I'm trying to show a "marker" on the map using ajax, but I haven't been able to find a solution despite searching various sources online. ================= Here's the code I currently have: var map; function initialize(){ var center = ...

Utilizing object properties to dynamically update components in VueJS

Are you familiar with dynamically changing a component using object props? App.vue <template> <div id="app"> <component :is="current['test'].target.name"> </component> <input type="bu ...

html displaying dynamic data in a table

As a beginner in coding, I am attempting to create a dynamic table. The first column is working fine with each new cell being added to the top. However, when I try to add columns, they fill from top to bottom instead of mirroring the first column. I want m ...

What is the best way to create a function that will initiate the download of a particular file based on a specific key provided by the

I need assistance in creating a function for my text box and button setup. Can someone please guide me on how to achieve this? The user will be provided with a specific alphanumeric key from the website. They must input this key into the text box and then ...

Can I send both a list of files and an entire JSON object in a FormData object to an ASP.NET CORE MVC Controller?

I'm looking for a way to send a formdata object to an MVC controller that includes both a JSON object with nested objects and a list of files. I've attempted to stringify the object into a JSON object, but the controller is unable to read the pro ...

AngularJS dropdown menu option selection using a filter to exclude already selected items

I am experiencing an issue with my code for select using ng-model. Everything is working fine except for the filtering functionality. When I remove the filter, duplicate options are shown for the already selected one. Therefore, I am attempting to filter o ...

Emscripten WebAssembly: Issue with Exporting Class "Import #13 module="GOT.func" error: the module does not exist as an object or function"

Exploring the potential of WebAssembly in a project as an importable function module, I decided to dive into using C++ with Emscripten. Implementing functions was smooth sailing, but running into obstacles when it comes to classes. My goal is to expose and ...

Refresh the controller variables displayed in the view

I'm currently working on a rails application and looking to refresh/reload the index method of my controller without refreshing the view. For example, here is my index method: def index @title = params[:title] end And the corresponding html.e ...

Selecting a chained dropdown option using jQuery in CodeIgniter

I'm struggling with jquery and ajax, particularly in implementing a select box functionality. I am using CI and below is my code. I want the data in another select box "category" to change dynamically based on the selection in the "brand" select box. ...

Is there a particular motive behind the decision for `arguments` to be treated as an object

Today while coding, I came across something puzzling. arguments.concat(someNumber); This line gave me an error for undefined function. Initially, I assumed that arguments was a native object for optimization purposes, but later discovered it's simp ...

Angular reactive forms can be customized to include a patched version of the matTime

I have an angular mattimepicker in my project. When trying to use it in a reactive form, I am encountering issues with patching the value to the edit form <h1>Reactive Form</h1> <form [formGroup]="form"> <mat-form-fie ...

What is the best method to eliminate elements from a queue using JavaScript?

I recently attempted to incorporate a queue feature into my JavaScript code. I found some helpful information on this website. While I successfully managed to add items to the queue, I faced difficulties when attempting to remove items from it. var queue ...

Matching an element that contains a specific string in JS/CSS

I'm currently faced with an HTML file that's being generated by an outdated system, making it tricky for me to control the code generation process. The structure of the HTML code is as follows: <table cellpadding=10> <tr> ...

What is the best way to hide the background of an extension's HTML?

Currently, I am working on developing a Chrome extension for a university project. However, I am facing challenges in making the background or body of the extension's HTML completely transparent to achieve a cleaner interface. The issue specifically l ...

Extracting information from an API

Hey there, good morning! I'm currently working on gathering car data from this website: My process involves sending a request through the search bar on the homepage for a specific location and date. This generates a page like this: From there, I us ...

The Bootstrap modal fails to open

I am currently working on implementing a Navbar button that triggers a Bootstrap modal containing a form. While looking for resources, I stumbled upon a useful script at https://gist.github.com/havvg/3226804. I'm in the process of customizing it to su ...

Why does Javascript Tic-Tac-Toe delay notifying the user until the entire board is full?

There have been a lot of questions about Tic-Tac-Toe javascript, but my issue is unique. My code works fine, but it doesn't declare a winner or a tie game until the entire board is filled. I suspect that my if statements are causing problems and can&a ...

What is the best way to convert a list of proxies into a JSON format of proxies?

I currently have a collection of proxy servers: proxies = [ "188.166.78.120:8080", "18.210.69.172:3128", "178.128.166.50:8118" ] However, the library I'm using requires the proxies to be structured in JSON format like this: proxies = { "htt ...

Can dynamic CSS imports be unloaded in a React application?

I am facing an issue with loading two files using react.lazy and suspense: import React, { Suspense, lazy } from "react"; import { Route, Redirect } from 'react-router-dom'; const MainLayout = lazy(() => import('Components/Layout/MainL ...