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

"Materialize and AngularJS: A dynamic duo for web

Currently, I am utilizing Materialize CSS for the design of my website and incorporating AngularJS to enhance its flexibility. However, I have encountered some issues with certain properties of Materialize (such as Select, date-picker, radio-button) not wo ...

Dropdown element vanishes upon selecting in HTML

Utilizing Angular's ng-init to populate a rest call function and populate $scope.races before filling up the dropdown. Initially, everything appears to be working correctly. However, upon selecting an option from the dropdown menu, it immediately cle ...

Troubleshooting Issue with Query Functionality in MEAN App's Find Request

I'm facing some challenges while working with queries in my MEAN App. Specifically, I am attempting to retrieve data that matches the input entered into a search field: $scope.searchInput = function(search){ $http({ method: 'GET', url: ...

What advantages can I expect for my client-rendered pages with Gatsby's Client Side Routing?

For a small site I developed, I utilized Gatsby for static content. However, for certain dynamically rendered content, I opted to employ client-only routes in Gatsby. Although I implemented a Header, Footer, and a specific font on my static site, these sa ...

Is there a way to broadcast a message to all the Discord servers where my bot is currently active using v14 of discord.js?

Can someone assist me in creating code that allows me to send a message to all servers at my discretion? I have not found any resources on this topic for discord.py or the newer versions of discord.js ...

Issues with v-on:change not triggering method in nuxt.js

Despite my efforts, I can't seem to get this seemingly simple task to work. I came across a question on Stack Overflow that seemed to address the issue - how to fire an event when v-model changes Here is the component that I am working with: <tem ...

On the hunt for a specialized JavaScript library for input validation?

Have you ever come across a JavaScript library that allows for variable validation in a convenient chaining style like this one? For example: if(insertLibraryNameHere(myNumberInput).int().min(0).max(10)) This library also has checks for other data types ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...

What is the best way to showcase the chosen items from a treeview in ReactJS?

I'm struggling to figure out how to showcase the selected elements from my treeview. Any ideas or tips? The main purpose of this treeview is to filter data for export purposes. You can find the original code here. import React, {useEffect, useState} ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

Invoke the REST API and save the compressed file onto the local machine

This is the code snippet I currently have: jQuery.ajax({ type: "GET", url: "http://localhost:8081/myservicethatcontainsazipfile", contentType:'application/zip', success: function (response) { console.log("Successful ...

The TypeScript factory class anticipates an intersection

In my code, I have a class factory called pickSomething that generates a specific type based on a key provided from a ClassMap: class A { keya = "a" as const; } class B { keyb = "b" as const; } type ClassMap = { a: A b: B } c ...

Having trouble with your Ajax post request?

I am currently working on creating a form that allows users to input information and submit it without the page refreshing. The processing of the form data will occur after the user clicks the submit button. To achieve this, I am utilizing jQuery and Ajax ...

JavaScript fails to focus on dynamically inserted input fields

Within my HTML template, there is an input element that I am loading via an Ajax call and inserting into existing HTML using jQuery's $(selector).html(response). This input element is part of a pop-up box that loads from the template. I want to set f ...

Utilizing BBC gelui within Joomla 3.0 for seamless integration

I am currently using Joomla! 3.0 with the Joomlashape Helix template and I am following a tutorial. You can check out the tutorial here. The tutorial mentions that I need to download RequireJS. Can anyone confirm if RequireJS is compatible with Joomla 3 ...

Why is the view not reflecting the updates made to the model?

I recently started delving into Angular JS and have been following tutorials to learn it. One issue I'm facing is that my model doesn't seem to update the view. Can anyone help me figure out why this is happening? Here is the code snippet: < ...

Self-moving button container

I have a challenge involving a button and a sliding div. When the button is clicked, I want the div to slide. The problem arises when I place the button inside the sliding div - it ceases to slide. I understand the issue at hand, but I'm unsure of ho ...

Press the button to access the URL within the current window

Working with Angular, I attempted to develop a function to open a URL in the current window. However, the code below within the controller actually opens a new window: $scope.openUrl = function(url) { $window.open(url); }; ...when using ng-click=&apo ...

Getting undefined while trying to iterate through data on a next js page using getStaticProps. What could be causing this issue?

Encountering difficulties while trying to output the page meta data in next.js when I execute: npm run build An error is thrown with the following message: Error occurred prerendering page "/blog/[...slug]". Read more: https://err.sh/next.js/pre ...

Information sent to a slot does not trigger a response

Trying to create a mobile-friendly chat app, I want to hide the new message button during conversations and use a different button on desktop. In addition, I have a dialog for creating new chat groups. <v-dialog transition="dialog-top-transition&qu ...