Creating a directive in AngularJS to automatically populate select options with custom values

As someone who is relatively new to creating directives, I am looking to develop a directive that will assist me in my application. What I aim to achieve is a select element directive that comes pre-populated with options and is self-contained. All I need to do in the end is connect an ngModel to it for data handling purposes. Here is an example of how my HTML markup looks:

<div custom-select 
 filter-by-humans="true" 
 ng-model="vm.selectedItem"></div>

Below is the AngularJS code snippet associated with this:

(function(){
'use strict';

 angular.module('app', [])
  .controller('customController', function(){
     var self = this;

     self.title = '';
     self.selectedItem = {};

     function initialize(){
        self.title = 'Custom select example';
     }

     initialize();
  })
  .directive('customSelect', function(){
     function helperCtrl(){
        var self = this;

        self.options = [];

        self.init = function() {
            self.options = [
                {id: 1, name: 'Option 1'},
                {id: 2, name: 'Option 2'},
                {id: 3, name: 'Option 3'},
                {id: 4, name: 'Option 4'}
            ];
        };
    }

    return {
      restrict: 'AE',
      replace: true,
      require: '^ngModel',
      scope: {
        filterByHumansOnly: '@',
        ngModel: '='
      },
      controller : helperCtrl,
      controllerAs: 'vm',
      template: [
        '<select ', 
        'id = "ddlOptions" ',
        'name = "options" ',
        'class = "form-control" ',
        'ng-options = "opt.name for opt in vm.options" ',
        'required ',
        'title= "select an option from the list"> ',
        '<option value="">select an option</value> ',
        '</select>'
        ].join(''),
      link: function(scope, element, attrs, ctrl){
        attrs('ng-model', scope.ngModel);
        ctrl.init();
      }
     };
  });
})();

Plunker Demo: http://plnkr.co/edit/XfLRD8pzBISvQgV1mRqd?p=preview

Thank you for your assistance and time.

Answer №1

Your quotation marks are incorrectly escaped in the ngOption attribute. The correct format should be:

template: [
    '<select ',
        'name="family" ',
        'class="form-control" ',
        'ng-options="(fam.firstName + \' \' + fam.lastName + \' (\' + fam.id + \')\') for fam in vm.family" ',
        'required ',
        'title= "select family member in drop-down-list"> ',
        '<option value="">select member</value> ',
    '</select>'
].join(''),

Demo: http://plnkr.co/edit/RLGc9dAElD1wpLN8uPm0?p=preview

Additionally, please note that it's require not

required</code. Since you have mistyped it, you can actually remove it altogether as it is not needed in this case (you are using scope <code>ngModel: '='
binding).

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

How can I close the menu when a menu item is clicked in a React.js application?

I am facing an issue where I want to close the menu when clicking on any menu item in React JS. The functionality works fine with a button icon but not with individual menu items. How can I resolve this problem? I have been trying to implement it using CSS ...

What causes the sudden disappearance of the returned value from AJAX?

This piece of code is what runs on my server: modify_emp.php <?php echo $_POST[id]; ?> Below is the Javascript code in my HTML page: <script> $(document).ready(function () { var alreadyClicked = false; $('.element').h ...

Implementation of Material UI Autocomplete feature with options consisting of an array of objects linking to both ID and label properties

Utilizing the Material UI Autocomplete component in my project has been a key feature. Referencing the official documentation, here are the available options: let options = [ { id: "507f191e810c19729de860ea", label: "London" }, { id: "u07f1u1e810c19 ...

Converting JSON to CSV using Angular

I need help converting a JSON object into CSV format using Angular. I found this npm package at https://www.npmjs.com/package/jsonexport that looks promising, but I'm not sure if it's compatible with Angular (seems to be node specific). Are there ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

How to Use Vanilla JavaScript to Fetch a JSON File, Convert the Data into an Array, and Iterate Through Each Object

Imagine having a JSON file called map.json: { "images":{ "background": ["images/mountains.png","images/sea.png"] } } The goal is for JavaScript to retrieve "images/mountains.png" from map.json and us ...

Include text into the iframe attributes

In my project, I am dynamically loading content into an iframe based on the results of a SQL query that is influenced by user input. This requires the height of the iframe to be adjusted regularly to maintain consistent page layout. Initially, when the pa ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...

jQuery UI tabs loaded with Ajax causing Javascript to malfunction

It appears that Javascript is disabled in jQuery UI tabs when loaded through ajax. Testing with jQuery tooltips and .click() alerts shows that Javascript functions properly in tabs not loaded through ajax (IDs present on the page). Below is the method use ...

In React, the functionality of rendering components conditionally is not functioning properly

I am looking to conditionally display either the Login component or Menubar component based on the value of the isLogin state. If the isLogin state is false, I want to render the login page. If it is true, I want to render the Menubar page. To achieve thi ...

Using blending modes with gradient colors in an SVG design

I'm struggling to get my logo to change colors upon scrolling into a button with similar gradient colors, but I just can't seem to make it work. Can anyone lend me a hand? Thank you! Take a look at my Logo. I've attempted to add some styles ...

What is the process for resizing a texture render target following a window resize event?

My intention was to improve the texture quality, but instead of achieving my goal, I encountered an issue where the same texture is being stretched over a larger area, resulting in unwanted staircase artifacts. I tried updating various elements like camera ...

Failed to execute test suite in React and Jest framework

While working on updates for our existing project, I encountered an error that is causing some of the tests to fail: FAIL src/components/changelog/__test__/ChangeLogOverView.test.tsx ● Test suite failed to run TypeError: Cannot create property & ...

What is the process for generating an array of objects using JavaScript?

I am struggling to create an array of objects using JavaScript and facing errors with new lines added where I need to split the messages and collect row numbers. The row numbers should be comma-separated if it is a repetitive error message. I found a solu ...

The type 'RefObject<HTMLDivElement>' cannot be matched with type 'RefObject<HTMLInputElement>' in this context

Encountered an error message: Issue with assigning types: Type '{ placeholder: string | undefined; autoComplete: string | undefined; "data-testid": string | undefined; onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement&g ...

How to Dynamically Update Sass Styles with Webpack 2?

Currently, I am in the process of setting up a React application that utilizes Webpack2, webpack-dev-middleware, and HMR for the development phase. One peculiar issue that I have encountered is related to updating .scss files. When I make changes to my .sc ...

Create a way to allow users to download html2canvas with a customized filename

I have a div where I want to use html2canvas to save a PNG file of its content. The issue is that the name of the saved file is static in my code and does not change unless I manually edit it. Is there a way to dynamically set the filename based on user i ...

Establishing the folder organization for Express Handlebars

I work with NodeJs, Express, and Handlebars. The main file for my server is named app.js const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); app.engine('handlebars', ex ...

Experiencing difficulties replicating two auto-scrolling divs

I have implemented a script to automatically slide two different divs. Here is the code I am using: The HTML: <div id="gallery"> <div id="slider" style="width: 6000px; left: -500px;"> <div><aside class="widget widget_testimoni ...

Unable to incorporate values into ng-model

Is there a way to get the code in ng-model to function properly so I can display both the first and last names? Essentially, what I am trying to achieve is to transform this: {{currentInventory.assigned.first_name + ' ' + currentInventory.assig ...