"Step-by-step guide on populating a select box with data from the scope

Hey everyone, I'm new to using Angular and hoping for some help with a simple question.

I've created a form (simplified version below) that I want users to see a live preview as they fill it out.

Everything was going smoothly with regular fields, but I've run into an issue with <select> fields.

<div ng-app="jobcreate">
    <div class="row fullWidth" ng-contoller="JobCtrl">

        <div class="medium-6 columns">

            <form method="POST" action="http://localhost:3030/job/create" accept-charset="UTF-8">

                <label for="title">Enter a title</label>
                <input placeholder="title" id="title" required="required" ng-model="job.title" name="title" type="text" />

                <br />
                <label for="title">Pick template</label> 
                <select ng-model="job.template" ng-options="template.Name for template in templates" name="template"></select>

            </form>     

        </div>

        <div class="medium-6 columns">

            <div class='job-detail {{ job.template || "default" }}'>
                <h2>{{ job.title || "Enter a title"}}</h2>
                <h2>{{ job.template || "Pick a template"}}</h2>
                <pre>Templates: {{templates | json}}</pre>

            </div>

        </div>
    </div>
</div>

Here is the relevant JavaScript code:

angular.module('jobcreate', []).controller('JobCtrl', function($scope) {
        $scope.templates = [
            {ID:'default', name:'Default'},
            {ID:'obnoxious', name:'Obnoxious'}
        ];

    });

You can check out a demo on jsfiddle here: http://jsfiddle.net/2m8jm/4/

While entering data in the title field works fine, I'm struggling to populate the select field with the contents of $scope.colors.

Answer №1

Within the fiddle provided at http://jsfiddle.net/2m8jm/4/, you initially utilized templates as a data array for the ng-options. However, there was no corresponding scope variable named templates within the controller JobCtrl. To rectify this, I renamed $scope.colors to

$scope.templates</code and made adjustments to the <code>ng-options
attribute - changing it to
ng-options="template.ID as template.name for template in templates"
.

A functional plunker demonstrating the corrected code can be found here: http://plnkr.co/edit/wsbxkjRqTEU2yfcHOV0D?p=preview

Additional Note:

Is there a way to prevent an initial empty value from appearing in the select field?

Indeed, there are a couple of approaches.

1) You can set an initial default value for job.template directly in your HTML markup like so:

<label for="title" ng-init="job.template='obnoxious'">Pick a template</label> 
<select ng-model="job.template" ng-options="template.ID as template.name for template in templates" name="template"></select>

2) Alternatively, define your controller with the following logic to assign a default value to job.template within the controller itself:

.controller('JobCtrl', function($scope) {
     // other lines of code        

    $scope.job = {};
    $scope.job.template = 'default';  
});

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

Rendering HTML strings instead of HTML in ReactJS

When I try to display HTML, all I see is strings var ref = firebase.database().ref('raffle/'); ref.on('value', (snapshot) => { var content = ``; var IDwrapper = document.getElementById('raffleFeed'); snapshot.forEac ...

Sending a form using an AngularJS dropdown menu

I have recently started using angularjs and decided to switch out a traditional html <select> box for an angular modal select box. The select box successfully populates with data from a $http ajax request, but I am facing issues with form submission ...

AngularJS allows us to dynamically generate button groups

I have a backend that defines datatypes, such as an enumeration for "sex" with values male and female. I need to render these dynamically in angularjs. { 'name': 'sex', 'type': 'enum', 'options': ...

What is the process for sending tinyEditory's content using ajax?

I recently incorporated the StfalconTinymceBundle into a Symfony2 project and it is functioning perfectly. However, I am encountering a problem when trying to submit the editor's content through AJAX. The editor's content does not seem to be bind ...

Is there a way to locate a specific word within a sentence using JavaScript

I have these lists of answers: For example: const answerList = [{index: 2, answer: nice}, {index: 5, answer: sunday} ...] similar to that Also, I have a sentence: For instance: "hi i'm theo nice to meet you. how are you" My goal is to identify ...

Learn how to showcase a modal pop-up in AngularJS by utilizing the ng-if directive

Hello, I am new to working with AngularJS. My question is how can I display a modal pop-up box when the ng-if statement evaluates to false? Can you please provide guidance on how to solve this issue? Here is an example of the code snippet in HTML: <di ...

Submit Form using Ajax - Update text in HTML element upon click

As I am working on developing a message system, I encountered an issue where the message content is not opening correctly in my template when clicking the "See" button. My intention is to implement an Ajax call that will replace the content with jQuery .te ...

Activate scroll function exclusively upon hovering over specific object

I am working on a page with an object that allows users to zoom in and out. I want to create a special zoom function that will be triggered when the user scrolls while their cursor is hovering over this object. If the cursor moves away from the object, th ...

What is the best way to retrieve AWS secret values using JavaScript?

Having recently started using AWS, I have been able to manually obtain the secret I need. However, when attempting to utilize the code snippet provided by AWS to retrieve the secret value, all my attempts result in undefined. Can someone please point out ...

Guide on seamlessly adding NPM "dependencies" to index.html using <script> tags in a VUE JS WEBPACK project

Are there any tools available that automatically inject or include NPM dependencies into the index.html file, similar to the GRUNT-BOWER plugin for BOWER dependencies? The project in question is a VUE-CLI WEBPACK project. Can this functionality be achieve ...

What is the process for reverting back to a previous version using n (Node Version Manager)?

After installing n(tj/n) to manage my node versions, I installed Node version 14.6 which automatically became the active version. When I tried to switch back using the n command, it only displayed the version I installed with n. Is there a way to switch b ...

Stuck with the Same Theme in the AppBar of material-UI?

Currently, I am attempting to modify the theme of a material-UI AppBar by utilizing states. Strangely enough, although the icons are changing, the theme itself is not. If you'd like to take a look at the code, you can find it here: https://codesandbo ...

Using ng-messages in a repeated md-input-container is a great way to efficiently display validation

Utilizing Angular 1.5.5 and Angular-Material 1.0.9, I have constructed an HTML form containing a repeated input element. My aim is to utilize ngMessages for displaying error messages. However, I am encountering an issue where the correct error message appe ...

Is it possible to manually input values when printing a PDF instead of pulling them from the main HTML?

I am facing a challenge in adding a "Print PDF" option to my website because it is built using Ext.js, and therefore the code is not in HTML. Despite searching for ways to print a PDF from the site, all solutions I found involve using HTML. Is there any li ...

On Internet Explorer 9, the window.open function is causing a new window to open up with

I am having an issue with redirecting my form to another page in a new window using window.open(). The problem I'm encountering is that when the new window opens, it appears blank and the original browser window redirects to the intended page for the ...

Updating the parent's data by modifying data in the child component in VueJS

When I use multiple components together for reusability, the main component performs an AJAX call to retrieve data. This data is then passed down through different components in a chain of events. <input-clone endpoint="/api/website/{{ $website->id ...

Ways to Implement Named Module Exports in Node.js Version 16 Application

Currently, I am working with Node 16.3.0 and Express 4.17.1 (although the Node version is open to change) In my project, I have a file named session.js structured as follows: // session.js exports.fetchUserId = async function(token){ ... } exports.sav ...

Currently, I am encountering a problem as I attempt to iterate through a dynamic table

I have a table containing various elements. An example row is Jack Smith with multiple rows like this: col1 col2 col3 col4 col5 col6 col7 col8 jack smith 23 Y Y error error_code error_desc The table is ...

What is the method to combine multiple style values in vue.js?

Is there a way to create a div with a box shadow where the values can be changed using a slider? I am having trouble using more than one value stored in a data variable. Any suggestions on how to achieve this? <div :style="{ borderRadius: x_axis y_ ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...