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

Is there a way to display a message box when the mouse cursor hovers over a text box?

Currently, I have set up 3 text boxes in my project. The functionality I am trying to achieve is when the user clicks on the second text box, the value of the first text box should be displayed in a message box (providing that the validation for the first ...

Typedoc Error: Attempted to assign a value to an undefined option (mode)

After installing typedoc with the command npm install typedoc --save-dev, I proceeded to add typedocOptions to tsconfig.json: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", // ...some lin ...

What are the steps to implement Lazy loading in Node.js?

const posts = await Post.find().populate("receiver").populate("author") try { res.json({ status: true, message: 'All posts fetched', data: posts.reverse() ...

Why is my Angular scope function being called twice instead of just once?

Check out the live demo here I have a quick question about the code snippet below. Even though I only call the function isSpecificPage() once, it seems to console.log twice. Any ideas why? <div ng-hide="isSpecificPage()"> <p>Hello!</p> ...

Sending a JavaScript value to PHP after a quiz has been completed

I've created a web page where users can take quizzes. These quizzes dynamically generate questions using JavaScript each time they are accessed. Disclaimer: I'm fairly new to JavaScript. Once the user completes the quiz, they receive their fina ...

When running the "react-scripts build" command and then serving it, the HTML files are being served instead

After successfully generating the build folder using react-scripts and running npm run build, I attempted to serve it locally with the npm package called serve by running serve -s build. The serve command started running on port 5000 without any issues. ...

Tips for inserting a blank space into a text box

It feels like such a simple issue, but my function is incorrectly returning "1" instead of just an empty space "" in my textbox. <td><input type="button" value="Space" name="Space" onClick='document.firstChild.search.value = document.firstCh ...

Utilizing Kendo UI Jsonp in conjunction with a WordPress json plugin: A comprehensive

Issue at Hand: My goal is to modify a kendo UI data-binding example to work with my own jsonp request. Description of the Problem: Starting from a data-binding example here, I have created this jsfiddle that demonstrates the desired functionality. To a ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

Re-rendering a Highcharts chart for optimal display

I have implemented Highcharts to showcase a set of data through different types of charts - Area chart, Line chart, and Bar chart. By default, the page loads with the Area chart displayed. Upon clicking a button, I switch to displaying the Line chart and t ...

JavaScript promises do not guarantee the execution of the loop

There was a block of Javascript code that I needed to modify. Initially, the code looked like this: if(!this.top3){ const promises = this.images.map((el, index) => { return this.getData(el.title, index); }); return Promise.all(promise ...

Conceal the parent component's <button> element within the Child component

I'm facing an issue with hiding a button in my parent component from the child component. I tried using props to bind the element and v-show directive to hide it, but instead of just hiding the button, it ends up hiding the entire tab. Take a look at ...

What is the process for retrieving the AJAX response text?

When it comes to my AJAX development, I rely on prototype and utilize the following code: somefunction: function(){ var result = ""; myAjax = new Ajax.Request(postUrl, { method: 'post', postBody: postData, content ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...

Personalize Drop-Down Selection

Currently implementing bootstrap on a site and seeking to enhance the dropdown menu customization. The default navbar appearance is present, with dropdown elements appearing upon hover. My goal is to include an icon next to each item in the navbar and ha ...

You will still find the information added with JQuery append() even after performing a hard refresh

After making an Ajax call using JQuery and appending the returned information to a div with div.append(), I encountered a strange issue. Despite trying multiple hard refreshes in various browsers, the appended information from the previous call remained vi ...

What causes an error when jqXHR.abort() is invoked in the beforeSend function?

Attempting to interrupt ajax call with beforeSend in case of a specific condition. Upon executing jqXHR.abort() or return false, I encounter the following error message: TypeError: $.ajax(...).fail is not a function .fail(function (jqXHR, textStatus, er ...

Displaying variables as HTML in Node.js involves rendering the variable data

Currently experimenting with displaying a Node.js variable as HTML. This is my setup in app.js using Express: Package.json "dependencies": { "body-parser": "~1.12.0", "cookie-parser": "~1.3.4", "debug": "~2.1.1", "express": "~4.12.2", ...

The Node.js promise failure can be unpredictable, despite being properly managed

In my journey to master MongoDB, I am currently exploring its capabilities by building a basic blog application. However, I have encountered an issue with the code responsible for saving blog posts - it seems to be inconsistent in its success rate, sometim ...

Display React component when clicked

As a newcomer to the world of React, I find myself intrigued by its potential. However, I am still in the process of grasping the fundamental concepts and would greatly appreciate any explanations provided. My goal is to display an 'About' compo ...