"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

Experiencing difficulties with mocha and expect while using Node.js for error handling

I'm in the process of developing a straightforward login module for Node. I've decided to take a Test-Driven Development (TDD) approach, but since I'm new to it, any suggestions or recommended resources would be greatly appreciated. My issu ...

Facing an issue with displaying a component error in a mat-form-field in Angular 9

I am looking to develop a shared component for displaying errors in Angular Material. Here is my shared component pfa-share-error: <mat-error *ngIf="fieldErrors(fieldName).required && fieldErrors(fieldName)"> Required </mat-err ...

Not prepped for EasyFB

Currently incorporating Easy Facebook for AngularJS (https://github.com/pc035860/angular-easyfb) into my project and encountering some inconsistencies in its functionality. Upon inspecting with console.log(ezfb);, I discovered the following: https://i.sta ...

The request to check the API at http://localhost/v5/api/checker returned a 404 error, indicating that

Trying to create a function that uses AJAX to call PHP, but encountering an error when clicking the button. Does anyone know how to solve this issue? Code provided below. PHP: $app->get('/checker', function () { $jsonContents = file_get_ ...

Encountering issues with extension CLI - "Unable to utilize the import statement outside a module"

Recently, I've been attempting to integrate the Afinn-165 node package (https://www.npmjs.com/package/afinn-165) into my Google Chrome extension. The goal is to analyze the sentiment of text scraped from each page. Being a novice in web development, I ...

Automatically save form field data every 15 seconds in AngularJS without using the $watch function

Is there a way to automatically save form field values every 15 seconds without using $watch? Additionally, the process should stop once the user navigates to a different form. Since there are multiple fields in the form, using $watch may cause performan ...

Having trouble with the ngSwipe feature?

I am currently developing a touch screen application for my client using AngularJS. In order to implement swipe functionality, I am utilizing ngTouch along with the directives ng-swipe-left and ng-swipe-right. I have also created functions that should be t ...

Establishing Redux States within the Provider (error: Provider encountering useMemo issue)

Exploring redux for state management has been a new journey for me. I am hoping it will help reduce API calls and increase speed, but I've hit a roadblock with an error that I can't seem to figure out. To troubleshoot, I created a simplified vers ...

Craft a FormType showcase using the dynamic duo of Ajax and Jquery

If you'd like to check out the code snippet for reference, please visit: This view serves as the canvas where innovation blends with execution. As I embark on this journey towards dynamic form creation, every step counts. Thank you for being part of ...

Encountering a 401 Error while trying to host an Angular app on Google Cloud Storage

I am currently facing an issue with deploying my Angular app to a Google Cloud Storage bucket. The bucket is public and set up to be served as a custom website via CNAME (test.example.com). The main page and 404 handler are mapped to index.html, but I am e ...

Finding the best way to transfer text between DIV elements?

I have a dilemma involving two DIV elements positioned absolutely on the sides of an HTML page, much like this EXAMPLE: <div class="left"> </div> <div class="right"> </div> These are styled using the following CSS: .left{ pos ...

Is it possible to extract my current location from one website and then access another website based on that location?

I am currently experimenting with an HTML5 script that loads a globe requiring users to click on it to determine the location. Once a location is clicked, another site opens displaying a map of the chosen location. Here is an example of the site with the i ...

Displaying a dynamic flag icon in a span element based on the selection from a mat-select

I am working on a mat-select component and I want to dynamically change a flag icon inside a span element in the mat-label based on the selected option. Currently, the initial flag is displayed correctly, but when I click on a different option, the flag d ...

Sloped Divider on the Upper Edge of the Page

I'm currently in the process of developing a new website, and I'm looking to create a unique design for the main navigation bar on the homepage. Here is the ideal layout that I have in mind: https://i.stack.imgur.com/pc8z4.png While I understan ...

Issue with getStaticProps not updating fetched values in Next.js production environment

I am currently working on building a blog using Next.js. Since the back-end is taken care of by another team, I am utilizing fetch API calls in getStaticProps to retrieve my articles, even though it may be considered best practice to interact with the data ...

Transferring files and information using the Fetch API

I am currently working on a React application and I have defined the state of my application as shown below: const [book, setBook] = useState({ title: '', cover: {} numberPages: 0, resume: '', date: date, }); The & ...

Using iScroll without animation by using scrolltoelement on an iPhone PhoneGap application

I've been working on an iOS PhoneGap app that uses Backbone and some other libraries. To handle scrolling, I implemented iScroll which has been functioning properly. However, I encountered a problem with the following code snippet: events: { &apo ...

Creating dynamic templates in AngularJS using ng-include and custom template directivesHow to implement dynamic

I would like to develop a div that can load various templates dynamically, depending on a context parameter: Introducing my "search-results-container" directive: app.directive("searchResultsContainer", function() { restrict: "E", templateUrl: "search ...

When a click event triggers, use the .get() method in jQuery to retrieve the content of a page and then update

I am currently facing an issue with a div class="contentBlock", which is acting as the container for updating content. <div class="contentBlock"></div> Unfortunately, the script I have written does not seem to be working properly :c $(docume ...

The React Stripe API is functioning perfectly on local servers but encountering issues in the live environment

Just when I thought I was almost finished, reality hits me hard! My deadline is right around the corner! I finally got everything working on my local machine with a stripe payment form. However, when I pushed it live, I received an error message from my A ...