Embed custom choices within directive using a 'select' element

I am facing a challenge with a directive that involves a select element populated with options loaded and cached through ajax.

The issue arises when I need to display specific options based on the context in which this directive is used. My initial idea was to dynamically include these extra options using transclusion:

<select-directive ng-model="model">
    <option value="x">custom option</option>
</select-directive>

The directive structure would be as follows:

{
            restrict: 'E',
            scope:{
                ngModel: '='
            },
            transclude:true,
            template:[
                '<select class="tipos" ng-model="ngModel">',
                    '<ng-transclude></ng-transclude>',
                    '<option ng-selected="ngModel === item.tipo" ng-repeat="item in ::tiposDoc track by item.tipo" value="{{::item.tipo}}" title="longer description">',
                        'description',
                    '</option>',
                '</select>'
            ].join(''),
            link: function(scope){
                $http.get('viewApp/viewCtrl.php/getTipos',{cache:true})
                    .then(function(response){
                        var resp = response.data;
                        if(!resp.success){
                            console.log(resp.log);
                            alert(res.msg);
                            return false;
                        }
                        scope.tiposDoc = resp.result;
                    });
            }
        }

However, the custom options are not being displayed within the select element. Am I overlooking something? Is there a workaround for achieving this customization?

Answer №1

This is one way to accomplish the task:

const addSelectOptions = (scope, element, attrs, ctrls, transclude) => {
    let htmlContent = transclude();
    element.find('select').append(htmlContent);
}

Answer №2

It appears that the use of ng-include tag causes a conflict with angular's select directive. To resolve this issue, I decided to include an optgroup element with the ng-transclude attribute, and fortunately, it solved the problem:

...
template:[
                '<select class="tipos" ng-model="ngModel">',
                    '<optgroup ng-transclude></optgroup>',
                    '<optgroup>',
                        '<option ng-selected="::ngModel === item.tipo" ng-repeat="item in ::tiposDoc track by item.tipo" value="{{::item.tipo}}" title="{{::item.tipoydesc}}">',
                            '{{::item.tipoydesc}}',
                        '</option>',
                    '</optgroup>',
                '</select>'
            ].join(''),
...

Maximus' solution also worked well for me, but I encountered difficulties when trying to integrate some specific functionalities with custom options.

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

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

Tips for modifying a state without triggering a re-render with the useState hook

I have a unique function onCondChange that triggers whenever the user modifies the value in the TextField. const onCondChange = (conds) => { updateState({ ...state, a: { ...state.a, conds }, b: ++state.b, }) } In this scenar ...

Rewriting a JSON tree structure in NodeJS

Exploring a new method in comparison to my previous post. The situation involves a JSON structure as follows: var data = { "tree": { "id": "99842", "label": "Bill", "children": [ { "id": "27878", ...

Click event triggers nested bootstrap collapse

As a beginner in bootstraps and coding, I am currently experimenting with opening the main bootstrap panel using an onclick event that includes nested sub panels. Here is my index.html file containing the panels and the button; <link href="https://m ...

transform data into JSON format and transmit using jquery ajax

I have one object: var myobject = {first: 1, second: {test: 90}, third: [10, 20]}; and I need to convert it into a JSON string using jQuery ajax. Can someone please advise on how to achieve this? (I tried using JSON.stringify(), but it didn't work ...

CORS issue encountered by specific user visiting the hosted website

I recently developed a bot chatting website using Django and React, which I have hosted on HOSTINGER. The backend is being hosted using VPS. However, some users are able to see the full website while others encounter CORS errors where the APIs are not func ...

Determining the exact number of immediate descendants within a ul element, while disregarding any script elements

Here is the HTML structure I am working with, which contains a script tag: <ul id="list"> <li class="item1"><a href="#">Item 1</a></li> <li class="item2"><a href="#">Item 2</a></li> <li ...

Searching for a substring within a larger string in JavaScript

I am trying to create a loop in JavaScript (Node.js) that checks if a string contains the "\n" character and then splits the string based on that character. <content>Hello </content><br /> <content>bob </content><br / ...

Can Vue allow for the inclusion of HTML elements to store data seamlessly?

One example involves displaying array elements in an <ul>, with each element starting with <li> and ending with </li>. Here is the attempted code: clearedtaskslist: function(){ this.template='<ul>' for(let i=0;i<t ...

The contents of a Javascript array are not appearing within a div element

I have developed a program that reads JSON data related to a concert event. The JSON file consists of an object named global, which includes details about the band name and venue. Additionally, there is a tickets object that contains information on all ava ...

Different ways to modify the CSS file of the bx-slider plugin for multiple sliders within a single webpage

Currently in the process of building a website using bx slider. I am looking to incorporate three sliders onto a single page for sliding HTML content. Initially, I added a bx slider to the page and customized it using CSS. I made modifications within jqu ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

Choose an option from a dropdown menu using JavaScript

Currently, I am working on a project that involves using javascrypt in conjunction with selenium. While attempting to search for and select an item from a list, I have encountered difficulties in selecting the element even after successfully locating it. I ...

Styling Input elements with a unified border in Bootstrap

[Issue Resolved] I have been working on setting a single border between multiple inputs inside a form-group in Bootstrap. Currently, the border is only visible when the input is not focused and it is the last one. However, my expectation is for the bo ...

MasteringNode: Exercise 3 The Beginning of My Journey with Input and Output

While working in Visual Studio Code on Windows 10 using powershell.exe as my terminal, I encountered a problem that I couldn't solve on my own. After numerous attempts, I decided to search the internet for a solution, and here's what I found: v ...

Issue with Chrome Extension in Selenium JavaScript WebDriver Test

I'm currently facing an issue with my Selenium JavaScript Webdriver test. Everything seems to be working fine, no errors are being thrown. The only problem is related to a Chrome Extension that is supposed to change the title of the page and then retr ...

Issue with Angularjs where changes to the view value are not reflected in the display

I have added an input directive for users to be able to undo actions. When the Enter key is pressed, the value is saved using a specific function, and pressing Esc should cancel edits and revert to the last saved value. However, I'm encountering an ...

Locate an item based on the `Contains` criterion by utilizing Express and Mongoose

Looking to find items in my collection that have userName containing adm. Expecting 2 results based on having records with userNames like admin0 and admin2, but the search returns nothing. The query being used is: Person .find({ userName: { $in: &a ...

Discover the proper way to utilize the orderBy function in AngularJS (1.2) to effectively sort data while preventing incomplete entries from moving around

Currently, I am working on implementing basic CRUD operations using AngularJS. Below is the code for the view: <table> <tr ng-repeat=="person in persons | orderBy:lastName"> <td> {{person.firstName}} </ ...

The service did not update the returned variable

I have been following this specific style guide when writing my Angular code: https://github.com/johnpapa/angularjs-styleguide The guide recommends structuring services like this: /* recommended */ function dataService() { var someValue = '&apo ...