Utilizing several bespoke directives simultaneously on a single webpage, complete with callback functionality

I have successfully developed a custom directive for a full-page date picker, with some assistance from Stack Overflow. This directive utilizes ngModel to capture the selected date and triggers a callback function that is set when the directive is inserted into the page. However, I encountered an issue where if I include two date pickers on the same page, it always invokes the callback function from the second date picker.

Below is the HTML code snippet...

<fp-date-picker ng-model="dateOne" on-select="dateSelectedOne()"></fp-date-picker>

<fp-date-picker ng-model="dateTwo" on-select="dateSelectedTwo()"></fp-date-picker>

Here's a condensed version of my directive implementation:

angular.module('directives').directive('fpDatePicker', ['$parse', function ($parse) {

    return {
        restrict: 'EA',
        require: 'ngModel',
        templateUrl: '/templates/fpDatePicker.tpl.html',

        link: function($scope, $element, $attrs, ngModel){

            var onSelectCallback = $parse($attrs.onSelect);

            $scope.selectedDate = moment();

            $scope.selectDate = function(day){
                var selectedDay = day.number;
                var selectedMonth = $scope.currentMonth.format('MM');
                var selectedYear = $scope.currentMonth.format('YYYY');

                $scope.selectedDate = moment(selectedYear + '-' + selectedMonth + '-' + selectedDay, 'YYYY-MM-DD');

                ngModel.$setViewValue($scope.selectedDate);

                onSelectCallback($scope);
            };

        }
    };
}]);

In case needed, here is the template for my directive....

<div class="fpDatePicker-controls">
    <a href="#" ng-click="previousMonth()">&lt;</a>
    <a href="#" ng-click="nextMonth()">&gt;</a>
</div>
<div class="fpDatePicker-month">
    <a class="fpDatePicker-day" 
        ng-repeat="day in currentMonth.days" 
        ng-click="selectDate(day)"
    >
        {{day.number}}
    </a>
</div>

I initially speculated that the issue might be related to global variables within the link function being shared among all instances of the directive or $attrs not corresponding to the attributes of the specific directive instance. However, after logging $attrs, I confirmed that they were unique for each instance.

I also considered whether making the scope isolated contributed to the problem, but since the callback functions are part of the scope whereas the expression in the attributes is an external attribute, this didn't seem to be the cause.

If anyone could provide insights or solutions, it would be greatly appreciated.

UPDATE: Plunker Demo Available

http://plnkr.co/edit/nU27Wjpu3UYCR9q6DnLw?p=preview

Answer №1

It seems that the problem stems from your directive lacking an isolated scope. This results in both directive instances sharing the same scope, leading to variables being overridden when the second directive is created.

To learn more about isolated scope, you can refer to the documentation here: https://docs.angularjs.org/guide/directive.

You can also view a demonstration of how to use isolated scopes in this Plunkr example: http://plnkr.co/edit/U64sbukqfFW0NQmvIC1a

I have made adjustments to your markup to ensure compatibility with the controller as syntax:

<body ng-controller="MainCtrl as main">
    {{main.dateOne}}
    <fp-date-picker ng-model="main.dateOne" on-select="main.dateSelectedOne()"></fp-date-picker>

    <br />
    <br />
    <br />

    {{main.dateTwo}}
    <fp-date-picker ng-model="main.dateTwo" on-select="main.dateSelectedTwo()"></fp-date-picker>

</body>

The key change in your directive definition is utilizing the scope attribute in the object to establish an isolated scope:

.directive('fpDatePicker', function() {

    return {
      scope: {
        select: '&onSelect'
      },

      restrict: 'EA',
      require: 'ngModel',
      templateUrl: 'datepicker.html',

      link: function($scope, $element, $attrs, ngModel) { ... }
     };
  })

Keep in mind that there are still issues with date selection in your code. Let me know if you require further assistance with resolving this issue.

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

Efficiently run multiple Node-written apps on a single server

I currently have a single VPS and would like to host multiple node.js apps on it, similar to how Apache or Nginx works. I am using Nginx as a proxy, but I have concerns. As you know, one of the key features of Node.js is its non-blocking I/O and sing ...

Passing selection from child to parent in ReactJS

When it comes to passing data from parent components to child components, using props is a common practice. But how can data be sent back up to the parent component? I'm working on a set of dropdown menus where users can make selections: DropdownMen ...

Tips for resetting the form input fields in Vue.js after the user has successfully submitted the form

I am facing an issue with my registration page. After the user enters some values and successfully submits the form, I want to clear all the fields. To achieve this, I am using a predefined function called reset() inside the script section. However, the ...

Creating an input field within a PixiJS Canvas: Enhancing PixiJS UI with typed-signals for seamless import/export interactions

I am trying to utilize PixiJS UI version 2.1.2 to add an input field to a canvas rendered by PixiJS version 8.2.0. The PixiJS part works fine, but I'm encountering issues with importing @pixi/ui. Firefox displays: "Uncaught SyntaxError: ambiguous ind ...

Customizing a thumbnail script to dynamically resize and display images according to their size properties

I am attempting to modify a simple JavaScript script that enlarges an image from a thumbnail whenever it is clicked. The issue I am facing is that the enlarged image is displayed based on a fixed width size. I want the enlarged image to be displayed accord ...

Is there an alternative method to including a PHP file from a remote server other than using the "<?php include(); ?>" syntax?

I have developed a PHP script that retrieves information from a MySQL database and I am looking to integrate this script (which contains extracted content from the database) onto various remote servers. These clients have websites built with Joomla/WordPre ...

Installing npm without the need for Node.js can be achieved

Looking to set up an ASP.NET Core Web Application in Visual Studio 2015 and have plans to incorporate AngularJs2 with TypeScript editing. To make this work, I need to set up the npm Package Manager. Ideally, I want to install npm without node as I will n ...

Alert from Google Chrome about Service Worker

My situation involves using FCM for sending web notifications. However, I am encountering a warning and the notifications are not functioning as expected when clicked (i.e., opening the notification URL). Below is my Service-Worker code: importScripts(& ...

eliminate item from list upon user clicking the button

Does anyone have any tips on how to effectively store and remove user-selected items from an object in JavaScript? I'm encountering an issue where only the first object in the array is being removed, and not the others. Any help would be appreciated! ...

Is there a way to automatically calculate the sum of two boxes and display the result in a separate

I am working with two boxes: one is called AuthorizedAmount and the other is called LessLaborToDate: <div class="col-md-6"> <div class="form-group"> <label>Authorized Amount</label> <div class="input-group"> & ...

Encountering JSON viewing issues post updating from version 3.1.11 to 3.2.0

After upgrading my app from version 3.1.11 to Grails 3.2.0, I encountered an issue with a failing call to an endpoint. Here is the stacktrace: ERROR org.grails.web.errors.GrailsExceptionResolver - StackOverflowError occurred when processing request: [GET] ...

Activate Pop-up for a single instance on BigCommerce

After researching and adding my own code, I am still struggling to get this question answered correctly. Here are the key points I am trying to achieve: 1. Automatically open a popup when the homepage loads. 2. Ensure that the popup is centered on all brow ...

JQueryMobile 1.3.2 encounters issues with popups following the installation of Chrome version 43.0.2357.65 m update

Is anyone else experiencing issues with the latest version of Chrome "43.0.2357.65 m" causing problems with JQueryMobile 1.3.2? When I try to click on a popup, it suddenly jumps to the top of the page and the scroll bar disappears. This was not an issue in ...

Adjust image source based on media query (CSS or JavaScript)

Is there a way to update the image src based on a media query with a maximum width of 515px? I'm considering using JavaScript, jQuery, or even AngularJS if there is an event equivalent to a CSS media query that can achieve this. I want to have differ ...

The PUT method in the Angular full-stack application is unable to perform updates in the

I'm encountering an issue while attempting to execute a PUT request to update the status of a problem from "unresolved" to "resolved". Unfortunately, I keep receiving a TypeError: $scope.details.$update(); is not recognized as a function. The framewo ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

The back button functionality in Android cannot be altered or overridden using JavaScript

Hey everyone, I'm currently in the process of developing a mobile application using phonegap. I'm facing an issue where I want to disable the functionality of the back button from navigating to the previous page. I simply want it to do nothing or ...

The angular error message is showing: [$parse:syntax]

I can't figure out what's going on with this code: <div ng-show="advices.length > 3" ng-click="advicesLimit = (advicesLimit == 3)?advices.length:3" class="event more_history" style="padding: 0px;margin: 0px;background-color: white;"> ...

Should the element be scrolled beyond a fixed-positioned element

Is there a way to determine if an element is scrolled behind another element that is fixed at the top? I am looking to trigger some javascript when an element is positioned below a fixed element and every height or scrollTop thereafter. I am attempting t ...

What is the reason for the output being [['a', 'b']], as opposed to [['a','b'],['c','d']]?

I've been working on the freecodecamp Bonfire: Chunky Monkey problem and I'm almost there with the solution. However, I'm stuck on why the output is [['a', 'b']], instead of [['a', 'b'], ['c' ...