How to retrieve element from templateUrl in AngularJS controller

I am facing a challenge in populating select(option) element inside a template html file from the controller. Although I have managed to do it successfully, I am unable to set a default value to avoid the initial empty option.

Here is a snippet from the template.html file:

...
<select name="drill_down" id="drill_down" ng-model="drill_down"
ng-options="item.value for item in items"></select>
...

And here is a snippet from the controller.js file:

(function () {
    'use strict';

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

app.config(function($stateProvider) {
    $stateProvider
        .state('appname', {
            url: '/appname',
            templateUrl: '/appname/template.html',
            controller: 'AppCtrl'
        });
});

app.controller('AppCtrl', AppCtrl);

function AppCtrl($scope, MyService) {
    $scope.college_majors_full = [];
    $scope.job_title_functions = [];

    MyService.getData().then(function(rows) {
        $scope.items = rows;   // this works - populates select options

        $scope.drill_down = $scope.items[0].value;  // this doesn't work
    });
...

If anyone has any suggestions or solutions, I would greatly appreciate your help. Thank you.

Answer №1

The characteristics of your options are limited to the text property of your items

You're mistakenly assigning a value instead of an id

Consider this approach instead

$scope.drill_down = $scope.items[0].value; 

Alternatively, you can create a value text type in the option

Try it like this

View

<select name="drill_down" id="drill_down" ng-model="drill_down"
ng-options="item.id as item.value for item in items"></select>

Controller

$scope.drill_down = $scope.items[0].id;

Answer №2

If you want to specify a default value using ngModel, you can do so easily. Take a look at this response for guidance on setting a default value for ngOption:

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

app.controller('optionsCtrl', function($scope) {
  $scope.prop = {
    "type": "select",
    "name": "Service",
    "value": "Service 3",
    "values": ["Service 1", "Service 2", "Service 3", "Service 4"]
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="optionsApp">

  <div ng-controller="optionsCtrl">
    <select ng-model="prop.value" ng-options="v for v in prop.values"></select>
  </div>

</div>

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

Streamline retrieval of alphanumeric indexing within json

When accessing json data using jquery, I came across an index structure like this: data.rows[0].student_1 data.rows[0].student_2 data.rows[0].student_3 and so on... Now, I'm looking to automate this process by creating a loop that allows me to acces ...

Display HTML content repeatedly depending on the number selected in a dropdown menu using AngularJS

I need your assistance with a dropdown selection feature on my website. The idea is that based on the number chosen from the dropdown, I want to dynamically repeat sections in HTML. For example, if I select 3 from the dropdown menu, the page should display ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

Firefox not clearing Highcharts points properly

I am currently utilizing highcharts to generate dynamic charts when hovering over a table row. My goal is to clear and hide the chart once the mouse moves away from the row. While this functionality works smoothly in Chrome, I am encountering a strange is ...

Determine the dimensions of a div element in IE after adjusting its height to auto

I am currently working on a JavaScript function that modifies the size of certain content. In order to accomplish this, I need to obtain the height of a specific div element within my content structure. Below is an example of the HTML code I am dealing wit ...

"Enhance Your Website with Drag-and-Drop Cart Functionality using HTML

Seeking assistance from anyone who has the knowledge. I've searched through similar questions on this platform but haven't been able to resolve my issue. Currently, I'm working on developing a basic shopping cart using HTML5 (Drag and Drop ...

Is it possible for me to utilize window.top within the .js file?

Within my GWT code, I am transferring a variable to a JSP file. The process looks like this: <html> <head> <script type="text/javascript"> alert("Inside the JSP file"); var criticalPath = window.top.criticalPath; ...

send parameter when clicking a link rather than using a hashtag

One interesting feature on my website is a menu link with the attribute title=.roc. When this link is clicked, I want to extract this attribute and click on an element with the same attribute on the destination page. Let's consider a scenario where I ...

Transforming an Axios image stream into a string by encoding it with Base64?

Currently, this is what I have in place: const Fs = require('fs') const Path = require('path') const Axios = require('axios') var {Base64Encode} = require('base64-stream'); const url = 'https://unsplash.co ...

Decoding GeoJSON: Extracting a feature from an array

I am currently working on a map project where I am drawing polygons with properties pulled from a JSON file. Each polygon is colored based on feature values in the JSON file. Here's an example of a feature in the JSON file: { "type": "Feature", " ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code: public String evaluate() throws Exception { // Code block here } I need assistance in using GSON JSON utility methods to convert the result s ...

Extract token from the URL and then use Axios in Vue.js to send it to the POST API

Hey there, I'm in need of extracting a token from the URL http://192.168.178.25:8080/register?token=eyJhbGciOiJIUzI... and then making a POST request to the API to confirm the account. I've attempted this but encountered a SyntaxError on the ...

issue with cordova-plugin-geolocation functionality on Android mobile device

Having trouble with the cordova-plugin-geolocation plugin in my ionic/cordova app. It functions perfectly on my browser and iOS device, but when I try it on Android, the map fails to display and does not acquire GPS coordinates. Instead, it times out and t ...

What is the best way to utilize Node.js to serve a single page HTML file on port 80?

This is how my project structure is organized: project assets/images/ css/application.css js/application.js font node_modules index.html server.js package.json I am aiming to run 'node server.js" in the project directory and have it serve on port ...

Changing the data request body in datatables ajax on button click

My goal is to initially fetch data when the page loads and then allow users to apply filters by clicking on them to fetch updated data. The query I am using is a POST request because it requires complex parameters that need to be formatted as JSON for bett ...

The random number generator in TypeScript not functioning as expected

I have a simple question that I can't seem to find the answer to because I struggle with math. I have a formula for generating a random number. numRandomed: any; constructor(public navCtrl: NavController, public navParams: NavParams) { } p ...

Having trouble locating the componentwillunmountafterInteraction in the React Native deck swiper

I've been utilizing react native deckSwiper in my project, but I'm having trouble unmounting it from the screen due to an error that says "ReferenceError: Can't find variable componentWillUnmountAfterInteractions". The error stack trace is s ...

Obtaining specific data from the forEach iteration, post-click event with JavaScript

Trying to access the value from a Tree-structured Array of Objects stored in Local Storage, Created a function that retrieves values from local storage using forEach and displays them on the screen. Clicking on the Yes/No button triggers the same functio ...

Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests. {"id": int, "hash": m ...