What is the best way to incorporate choices into a dropdown menu using an AngularJS directive?

Looking to prefilled a select tag used for country selection with options using a directive:

<select class="countryselect" required ng-model="cust.country"></select>

The custom directive I've created is as follows:

return {
  restrict : "C",
  link: function postLink(scope, iElement, iAttrs) {
     var countries = [
        ["AND","AD - Andorra","AD"],
        ["UAE","AE - Vereinigte Arabische Emirate","AE"]
        ... //loop array and generate opt elements
        iElement.context.appendChild(opt);
    }
  }

Although I am successfully adding additional options to the select, I am facing an issue with the ng-model binding. Even when cust.country has a value (e.g. "UAE"), the option is not selected.

Any suggestions on how to ensure that the select displays the value of cust.country? I suspect there might be a timing problem at play here.

Answer №1

Utilize the directive feature of Angular JS:

Code Snippet:

<div ng-controller="MainCtrl">
<select ng-model="country" ng-options="c.name for c in countries"></select>
{{country}}
</div>

Script Section:

app.controller('MainCtrl', function($scope) { 
   $scope.countries = [
    {name:'United Arab Emirates', value:'AE'},
    {name:'Andorra', value:'AD'},
  ];

  $scope.country = $scope.countries[1]; 

});

Refer to the select documentation: Angular Select

ENHANCEMENT WITH DIRECTIVE

Custom Directive:

  app.directive('sel', function () {
    return {
        template: '<select ng-model="selectedValue" ng-options="c.name for c in countries"></select>',
        restrict: 'E',
        scope: {
            selectedValue: '='
        },
        link: function (scope, elem, attrs) {
            scope.countries = [{
                name: 'United Arab Emirates',
                value: 'AE'
            }, {
                name: 'Andorra',
                value: 'AD'
            }, ];
            scope.selectedValue = scope.countries[1];
        }
    };
});

Main controller Function:

app.controller('MainCtrl', function($scope) {

  $scope.country={};

})

Updated Code:

<div ng-controller="MainCtrl">
<sel selected-value="country"></sel>
{{country}}
</div>

See a working example here: EXAMPLE

Answer №2

To make this function properly, you must include the options in the ngModelController. Here is an example of how to do it:

return {
    restrict : 'C',
    require: ['select', 'ngModel'],
    link: function(scope, element, attrs, controllers) {
        var countries = [['A', 'text text']];
        countries.forEach(option => {
            const optionElement = angular.element('<option/>')
                .attr('value', option[0])
                .text(option[1]);

            element.append(optionElement);
            controllers[0].addOption(option.value, optionElement);
        });
    }
};

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

Create a Jest unit test for a specific function

I started my first unit test in react with jest this afternoon. The initial 5 tests I need to do involve testing the return functions, which isn't too difficult. However, I'm struggling to understand how to perform unit testing on my login funct ...

`Need help testing flow.js file uploads using Selenium?`

My AngularJS SPA allows users to upload files using the ng-flow wrapper for flow.js. I am currently in the process of setting up automated e2e tests with Selenium, but I am facing challenges when it comes to testing the file uploading mechanism triggered b ...

Managing objects over time in Three.js

I am looking to dynamically add and remove objects in a continuous stream. Imagine having an array of 50 objects, and I want to cycle through them with a period, essentially creating an object stream. I initially attempted using setTimeout and setInterval ...

Retrieve information attribute within VueJS

Within a v-for loop, I am utilizing a select form in the following manner: <div class="select"> <select v-model="shippingMethod"> <option value="{{shipping.id}}" v-for="shipping in shippingMethods" data-price="{{ shipping.amount ...

Implement a Basic Custom Shader on a Cube in Three.js

Struggling with applying a basic custom shader to a cube in Three.js. Whenever I attempt to use the shader, the cube mysteriously vanishes. No issues when using a standard Toon or Lambert Material - cube rotates and behaves as expected. Oddly, Orbit Contr ...

The input field in Angular dynamically populates values into multiple instances of the same text

I am facing an issue with my comment inputs where whatever I type in one input is automatically populated in all other inputs. How can I ensure that the text input value only appears in the input box that I am typing into? Below is a snippet of the templa ...

Determining the type of index to use for an interface

Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties. interface Dog { dog: { sound: string; } } interface Cat { cat: { lives: number; } } type CatOrDog = Cat | D ...

The overall outcome determined by the score in JavaScript

Currently, I am working with a dataset where each person is matched with specific shopping items they have purchased. For instance, Joe bought Apples and Grapes. To gather this information, individuals need to indicate whether they have made a purchase. I ...

My data is not appearing with ng-repeat or ng-bind

One issue I am encountering is that my ng-repeat / ng-bind is not displaying the data within $scope.articles, even though I am getting the expected data in the console. To help identify the problem more easily, I have created a code snippet below: var A ...

The PHP query that was sent through an AJAX POST request is not being executed correctly

I have a situation where I am working with two pages: Page 1: <input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/> <input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/& ...

Looking to ensure that the appropriate error validation message displays when an incorrect username is entered and submitted within an Angular JS application

I am working on binding the error message and testing it. Here is the code snippet I am using: <div class="col-md-9 col-xs-12"> <strong class="text-danger ng-binding" title="Invalid Username"> ...

Can items containing various conditional fields from a collection be published simultaneously?

Imagine a scenario where there is a party object containing various information fields such as location, time, guests, etc. Additionally, there are privacy settings like showLocation and showGuests to hide certain details from uninvited users. The challen ...

Steps to divide input form data and transmit it to MySQL

I am currently facing a challenge with my form, as it works perfectly when making calls to the server. However, I would like to enhance its functionality by allowing it to handle multiple input codes submitted by users. My main question is how can I modi ...

Encountering a problem with TypeScript while employing Promise.allSettled

My current code snippet: const neuroResponses = await Promise.allSettled(neuroRequests); const ret = neuroResponses.filter(response => response?.value?.data?.result[0]?.generated_text?.length > 0).map(({ value }) => value.data.result[0]?.genera ...

Tips for effectively using query parameters with UI router in AngularJS

I'm new to AngularJS and still in the process of learning. I have a task where I need to extract query parameters from $stateparam. Is there a way to achieve this? URL example: https://..../details?param1=abc&param2=10 In my UI route, I currentl ...

Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...

I can't figure out why the callback function for my $.get() request is not being triggered when I send data to the Express

Could anyone help me understand why my callback function is not being called properly? $.get("http://localhost:8080/", msg, function(data) { alert("Data" + data); }); It seems like the server receives the reque ...

The issue of jQuery not loading within Ajax content has been resolved

Appreciate the assistance provided. I am facing an issue where my jQuery code does not load within ajax content. Below is the code snippet from index.html : <script language="javascript" type="text/javascript"> $(function() { $("#gps").load("find. ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

Error: Attempting to destructure without initializing / identifier 'name' is already in use [mysql][nodejs]

Whenever I attempt to pass keys as parameters, I'm encountering these errors in nodemon: SyntaxError: Identifier 'name' has already been declared This is the model function causing the issue: const create = async (name, about, site) => { ...