Dynamically incorporating Angular UI Datepicker into your project

For my project, I am required to include a dynamic number of datepickers on the page. I attempted to accomplish this using the following method (Plunker):

Script:

var app = angular.module('plunker', ['ui.bootstrap']);    
app.controller('MainCtrl', function($scope) {
  $scope.openDatePicker = function($event) {
    $event.preventDefault();
    $event.stopPropagation();

    $scope.opened = true;
  };

  $scope.dateOptions = {
    formatYear: "yy",
    startingDay: 1,
    format: "shortDate"
  };

  $scope.details = [{
    "parameterValue": "2015-08-12"
  }, {
    "parameterValue": "2015-08-12"
  }, {
    "parameterValue": "2015-08-12"
  }, {
    "parameterValue": "2015-08-12"
  }];
});

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
  <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
  <script src="script.js"></script>
</head>

<body>
  <div ng-controller="MainCtrl">
    <form name="detailsForm" novalidate ng-submit="submitForm(detailsForm.$valid)">
      <div ng-repeat="item in details" class="input-group">
        <input ng-model="item.parameterValue" type="text" class="form-control" id="datePickerItem" datepicker-popup="shortDate" 
        is-open="opened" datepicker-options="dateOptions" current-text="Today" clear-text="Clear" close-text="Close" ng-readonly="false" />
        <span class="input-group-btn">
          <button type="button" class="btn btn-default" ng-click="openDatePicker($event)"><i class="glyphicon glyphicon-calendar"></i></button>
        </span>
      </div>
    </form>
  </div>
</body>
</html>

The issue arises when I attempt to open one datepicker, all others also open (due to sharing the same $scope.opened variable). Additionally, once closed, they cannot be reopened.

Is there a more elegant solution to address this problem?

Thank you.

Answer №1

All the datepickers currently have the same id="datePickerItem".

In HTML, the id attribute should always be unique. To fix this issue, you can try using:

id="datePickerItem_{{$index}}"

This will append the current index of the ng-repeat to the id, ensuring that each id is unique. It will also prevent all datepickers from opening simultaneously.

Additionally, you are using a single shared opened variable for all datepickers.

You can update your code as follows:

<div ng-repeat="item in details" class="input-group">
    <input ng-model="item.parameterValue" type="text" class="form-control" 
        id="datePickerItem_{{$index}}" datepicker-popup="shortDate" 
        is-open="opened[$index]" datepicker-options="dateOptions" current-text="Today"
        clear-text="Clear" close-text="Close" ng-readonly="false" />
    <span class="input-group-btn">
        <button type="button" class="btn btn-default" ng-click="openDatePicker($event, $index)">
            <i class="glyphicon glyphicon-calendar"></i>
        </button>
    </span>
</div>

Also, update your controller with:

$scope.opened = [];
$scope.openDatePicker = function($event, index) {
    $event.preventDefault();
    $event.stopPropagation();

    $scope.opened[index] = true;
};

Don't forget to set $scope.opened[index] to false when closing the datepicker.

Answer №2

Give this a shot:

$scope.showModal = function($event, modalName) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope[modalName] = true;
    };

Then in your HTML:

ng-click="showModal($event, 'modelName')"

Answer №3

Why not set the opened property on the repeat object?

For example:

<div ng-repeat="item in details" class="input-group">
    <input ng-model="item.parameterValue" type="text" class="form-control" 
        id="datePickerItem_{{$index}}" datepicker-popup="shortDate" 
        is-open="item['opened']" datepicker-options="dateOptions" current-text="Today"
        clear-text="Clear" close-text="Close" ng-readonly="false" />
    <span class="input-group-btn">
    <button type="button" class="btn btn-default" ng-click="openDatePicker($event, item)">
        <i class="glyphicon glyphicon-calendar"></i>
    </button>
</span>

And in the controller:

$scope.openDatePicker = function($event, item) {
    $event.preventDefault();
    $event.stopPropagation();

    if(item.opened){
        item.opened = !item.opened;
    } else{
        item.opened = true;
    }
};

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

Trigger an alert when a button is clicked and redirect the user to an newly opened tab

I recently created a button with a link that opens in a new tab. I also implemented some JavaScript to display an alert. Everything is working as expected, but after the user clicks "OK" on the alert, they remain on the same page. I would like to automati ...

The window.onload function is ineffective when implemented on a mail client

Within my original webpage, there is a script that I have created: <script> var marcoemail="aaaaaa"; function pippo(){ document.getElementById("marcoemailid").innerHTML=marcoemail; } window.onload = pippo; </script> The issue a ...

Conceal HTML elements from the bottom as new content is being added dynamically

I am currently working on a comments feed feature. By default, only the first four comments are displayed, with an option to show more when clicking the "show more" anchor. The issue I'm facing is that if new comments are dynamically added, the CSS hi ...

Implementing a time to live feature in socket.io can be accomplished by setting a

After extensive searching online, I haven't been able to find any resources on how to implement the 'time-to-live' function using Socket.io. In my project, I am utilizing Node.js with express. The functionality of the mentioned time-to-live ...

Adjusting the visibility of a div as you scroll

I'm trying to achieve a fade-in and fade-out effect on div elements when scrolling over them by adjusting their opacity. However, I'm facing difficulties in getting it to work properly. The issue lies in the fact that my div elements are positio ...

What is the process for duplicating a set of elements within an svg file and displaying the duplicate at a specific location?

SVG <svg width="200" height="200"> <g id="group"> <rect x="10" y="10" width="50" height="20" fill="teal"></rect> <circle cx=" ...

Is it possible to deactivate a form control in AngularJS using a variable?

I am facing a situation where I have three distinct user roles - Coordinator, Resource, and User. Within my form, there are several controls that need to be disabled or set to read-only based on the user role, specifically for the User role while remaining ...

Passing a variable between pages in PHP: a simple guide

In my *book_order* page, I allow users to input orders into a table called *order_management*. The order_id is auto-incremented in this table. After submitting the page, I need to pass the order_id to another page named *book_order2* where products can be ...

What are the best practices for setting access permissions when using Azure AD authorization flow?

I am in the process of creating a small Next.js application with the following structure: Authenticate a user via Azure AD using Next-Auth Allow the user to initiate a SQL Database Sync by clicking a button within the app with the access token obtained du ...

Tips for generating an input element using JavaScript without the need for it to have the ":valid" attribute for styling with CSS

My simple input in HTML/CSS works perfectly, but when I tried to automate the process by writing a JavaScript function to create multiple inputs, I encountered an issue. The input created with JavaScript is already considered valid (from a CSS ":valid" sta ...

JavaScript event manually triggered not propagating within an element contained in an iFrame context

I am currently developing a WYSIWYG designer that enables users to choose colors through [input type="color"] fields. The interface includes inputs on the left side and an iFrame on the right side displaying the generated preview. Normally, when ...

Is there a way to automatically scroll vertically to a specific line in HTML?

Trying to explain this is a bit tricky. I am looking to add an element to the HTML that prompts the browser to scroll vertically to its location automatically when loaded, similar to an anchor. So: | visible area | | content html | | content html | ...

Insert some text into the div element. Create a new line

I'm looking to make a specific text on my webpage trigger a new line when displayed in a div. I've been struggling to figure out how to accomplish this: var original= "the text @n to change"; var changed = original.replace(/@n /g, '\ ...

Issue with popup display in React Big Calendar

I'm currently working on a calendar project using React-Big-Calendar, but I've run into an issue with the popup feature not functioning properly. <div className={styles.calendarContainer} style={{ height: "700px" }}> <C ...

Node.js Error: The object does not have the specified method

Recently, I dived into the world of node.js by following a fantastic tutorial on node.js, express, and mongodb from Howtonode. However, I encountered an error that doesn't seem to have been addressed in the comments section. The last comment was made ...

Is it possible to automate the firing of setTimeout events using WebDriver?

Looking to test pages with numerous setTimeout functions, I'm searching for a way to expedite the code execution upon page load rather than waiting for it to run on its own. One idea is to inject custom JavaScript like this into the page before evalu ...

Can you explain the concept of a "cURL" and guide me on how to use it effectively?

I'm currently working on setting up a Lyrebird application, but I only have a basic understanding of javascript and php. Despite my efforts to implement a cURL request from , I've encountered issues trying to get it to work in both javascript and ...

Issue with process.env.NODE_ENV not functioning appropriately in NodeJS when utilizing package.json scripts

I currently have three separate databases configured for testing, development, and production purposes. My goal now is to make my express app switch between these databases based on the script that is being executed. These are the scripts I am using: "s ...

A guide to resetting items directly from a dropdown select menu

I need help with clearing or resetting select options directly from the dropdown itself, without relying on an external button or the allowClear feature. Imagine if clicking a trash icon in the select option could reset all values: https://i.stack.imgur. ...

The Django application is failing to interact with the AJAX autocomplete functionality

After typing the term "bi" into the search bar, I expected to see a username starting with those initials displayed in a dropdown list. However, nothing is showing up. Here are the codes I have used: search.html <html> <div class="ui-widget"> ...