Tips for developing a directive that supplies values for ng-options

I have select elements with the same options throughout the entire app, but they may vary in appearance. For example, selects for a user's birthday (day, month, year).

Is it possible to create a directive that can provide values or expressions for ng-options?

For instance,

<select my-options-months></select>
, where my-options-months would automatically generate options with values ranging from 1 to 12 using the ng-options directive.

Answer №1

Revised solution To implement your directive, follow these steps:

var app = angular.module('app', []);
app.controller('MainCtrl', function ($scope) {
    $scope.selectedMonth = 3;
})
    .directive('customMonthOptions', function ($compile) {

    return {
        priority: 1001, // ensures this directive is compiled first
        terminal: true, // prevents lower priority directives from being compiled after it
        compile: function (element, attrs) {
            element.attr("ng-options", "m for m in months");
            element.removeAttr('custom-month-options'); 
            var func = $compile(element);
            return function (scope) {
                scope.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
                func(scope);
            };
        }
    }
})

Please refer to the example on JSFiddle for more details: http://jsfiddle.net/KN9xx/39/

Answer №2

If you're looking to generate a series of values for selection, consider using a template. For dynamic ranges, simply connect it to an attribute in a directive.

app.directive('myOptionsMonths', function(){
  return {
    scope: {
      myOptionsMonths:"@"
    },
    link: function(scope,e, a){
      var N = +a.myOptionsMonths;
      scope.values  = Array.apply(null, {length: N}).map(Number.call, Number);
    },
    template: "<select ng-model='t' ng-options='o for o in values'></select>"
  };
}); 

<my-options-months my-options-months="10"></my-options-months>

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

Answer №3

Perhaps a different strategy could involve implementing a filter like this:

.filter('customRange', function () {
        return function (values, minimum, maximum, addPadding){
            minimum = parseInt(minimum);
            maximum = parseInt(maximum);
            addPadding = addPadding ? addPadding : false;
            for (var num=minimum; num<=maximum; num++){
                values.push(addPadding ? ("00" + num).slice (-2) : num + '');
            }
            return values;
        };
    })

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

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...

Receiving undefined properties in functional React components

Is it possible to pass the {requests} prop to the RequestRow component correctly, especially after the setRequests function is executed? The issue seems to be that when requests are initialized as undefined initially and then set with an asynchronously cal ...

Retrieve the values and IDs for every span element within the form

I have been attempting to retrieve all span elements within a form and make them editable input text fields. Once you click away, they should revert back to span elements. I will provide a live example in the attached fiddle. I tried my hand at it, but the ...

What is the best way to pass data from the server to a Vue CLI application?

I am looking for a way to connect my Vue CLI app to a server back-end. The server will send a view template along with data payload, and I need to inject that payload as JSON into the Vue app as a data property. Here is a snippet of the index.html file ge ...

What is the process for executing code on a server by clicking a button?

In my Next.js application, there is a file named dummy.js with the following content: class Dummy extends React.Component{ static async getInitialProps(ctx){ return { dummy : 'abc'}; } displayHelloWorld(params) { cons ...

Utilizing React for incorporating HTML5 canvas gradients

I'm currently working on an app that allows users to generate a background gradient with two distinct colors using React. The issue I'm facing is that while the first color appears correctly, the second color ends up looking more like a solid col ...

Using JQuery to Load a CSHTML File into a Modal in C#

I am attempting to have the content of one specific page loaded into a modal on a different page when a button is clicked. Unfortunately, I am encountering an issue where not only the desired content from the specified page is loading, but also content fro ...

Dealing with Content-Range for pagination in Restangular: A comprehensive guide

When working with an API that returns the header "Content-range" for lists, how can I efficiently retrieve and parse this header value using Restangular? Do I need to create a custom function for this task? Is there an existing method in Restangular that ...

Safari experiencing hang after successful CORS OPTIONS request

Safari (10 - OSX El Capitan) Issue with CORS Encountering a problem with CORS while performing a POST request from an AngularJS front-end to a Laravel back-end. In Chrome and Firefox, both OPTIONS and POST requests return http status 200 OK In Safari 10 ...

Revamp the Vue component for better DRYness

Seeking advice on a more efficient way to improve the code below and make it DRY: <h2>{{ title }}</h2> <p>{{ subtitle }}</p> I am currently checking this.name for both the title and subtitle, wondering if there is a better implemen ...

Developing dynamic HTML content using Android and JavaScript to insert JavaScript code into the head tag dynamically

I need to incorporate a banner into my Android application in a specific way. Upon receiving the following Javascript code from the server: <script type="text/javascript" src="http://rm.face.ua/adriver.core.2.js"></script> <div id="adri ...

Encountering issues with managing CometD channels within Angular 2

After dabbling in Angular2 and Typescript, I decided to challenge myself by creating an application using plain javascript with the CometD library. The goal of this app was to retrieve data from a CometD channel and present it to the user in some way. So, ...

Invoking PHP function within a specific class using Ajax

I am currently utilizing Zend Framework. My PHP class is structured as follows: FileName : AdminController.php Path : /admin/AdminController.php Ajax Function : function exportToExcel() { $.ajax({ url: "/admin/AdminController/testFunction", ty ...

Issue with submitting a form within a React modal - lack of triggering events

I am utilizing the npm package react-modal (https://www.npmjs.com/package/react-modal) in my project. The issue I am facing is that when I click on 'Submit', nothing happens. The function handleSubmit</a> is not being triggered, as no conso ...

Divide JSON arrays into separate select boxes

I have integrated AngularJS into certain sections of my website, rather than using it for the entire site. Currently, I am dealing with a scenario where I have a pair of select boxes, one dependent on the other. One box contains a list of countries, while ...

Retrieve the highest value from 4 different JSON source URLs

After retrieving values from a JSON URL, using the following code: $(document).ready(function () { function price(){ $.getJSON('https://poloniex.com/public?command=returnTicker', function(data){ document.getElementById('Polon ...

Considering the development of a web application similar to Canva

I'm interested in creating an app similar to Canva, but I'm not sure where to begin. I have a solid understanding of HTML and CSS, but my JavaScript skills are basic. I'm curious about the technologies they use. Is there a way to save HTM ...

Creating flexible Vue routes using a single router component and a navigational menu

I am working on a Vue project and I want to implement nested routes in my router.js. My goal is to have just one menu for all the nested routes and only one <router-view></router-view> in a master component. This is what I envision (in pseudoc ...

Express encounters difficulties loading JavaScript files

I'm currently working on building an express web app, but I'm encountering a problem with importing a javascript file. Within board.js, there's a line const utility = require('./utility');. However, this line is causing an error: ...