Only one of the two directives defined in the same file has the ability to access moment.js

There are two custom directives in the code snippet below, both of which rely on the moment.js library. However, when these directives are applied within the same template, an issue arises where one directive can access the moment function while the other cannot (resulting in a value of undefined).

Here is an example of how the directives are used within the same template:

The Template

<datepicker date-format="yyyy-MM-dd">
    <!-- Works correctly -->
    <input required ng-model="vm.dateFrom" moment-now />
</datepicker>

<datepicker date-format="yyyy-MM-dd">
    <!-- Throws an error -->
    <input required ng-model="vm.dateTo" moment-then />
</datepicker>

The Module

;(function() {

    "use strict";

    angular.module('dateUtils', [])
        .directive('momentNow', momentNow)
        .directive('momentThen', momentThen);

    function momentNow() {
        return {
            /* Parameters are omitted */
            link: function(scope, element, attrs, ngModel) {

                console.log(moment);

                var value = moment().format(scope.momentFormat || 'YYYY-MM-DD');
                ngModel.$setViewValue(value);
                ngModel.$render();
            }
        }
    };

    function momentThen() {
        return {
            /* Parameters are omitted */
            link: function(scope, element, attrs, ngModel) {

                console.log(moment);

                var currentMoment = moment();
                var format = scope.momentFormat || 'YYYY-MM-DD';
                var value = (currentMoment.hours() >= 20 ? currentMoment.add('days', 1) : currentMoment).format(format);

                ngModel.$setViewValue(value);
                ngModel.$render();

            }
        }
    };

}());

Answer №1

Change the name of your variable in this section:

var currentTime = moment();

You are masking the original moment variable with your new one.

If you're confused as to why console.log(moment); is displaying undefined, read up on what is known as hoisting.

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

The page action icon is visible exclusively on the extension's page

Currently, I am delving into the world of creating chrome extensions. One interesting feature that caught my attention is page actions, which allows developers to display an icon within the address bar. Let me share with you a snippet of my code: First, i ...

What causes the movement of li elements when hovered over and moved away from?

While trying to highlight a specific list item (li) element on mouse hover and simultaneously hide others using a script, an issue arises. The highlighted element "something" changes its position during hover, causing it to move out of the mouse cursor&apo ...

Generating a string indicating the range of days chosen

Imagine a scenario where there is a selection of days available to the user (they can choose multiple). The list includes Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, each with an associated number from 0 to 6. For instance, Sunday ...

What is the best way to send data from a header component to a separate container component?

Utilizing React-router-dom, I am able to seamlessly switch between components in the following setup: <Router> <div> <Header /> <NavigationBar /> <Switch> <Route exact path ...

Accessing Google Sheets with the default login information

I have data stored in Google sheets and I am utilizing the Sheets API for Node.js to retrieve this data. To authenticate, I am using Service Account JSON to create a JWTClient. Accessing the data through the Sheets API is functional and everything is runn ...

What is preventing me from generating a new User account?

I'm currently working on setting up a register and login server using node.js and mongoose. I have created a user model and a user route, but for some reason, I am unable to successfully create a new user. When I try to connect to Postman using POST : ...

Steps for executing Mocha tests in a specified sequence

Background Currently, I am developing a Node.js program where I am creating test suites in Mocha using Chai and SinonJS. The program involves a core graphics module that manages access to a node-webgl context. Due to the nature of node-webgl, I want to i ...

Update the table contents smoothly using the html helper PagedListPager without having to reload the entire

I am struggling with a specific line of code that utilizes the html helper's PagedListPager: @Html.PagedListPager(Model.kyc_paged_list, page => Url.Action("ClientDetails", new { id = ViewBag.ID, kyc_page = page, transaction_page = Model. ...

Setting up state when a new window is launched

Let's consider a scenario where I already have a JWT token stored in cookies and the state contains a status flag for LoggedIn: true/false. The goal is to remain logged in when opening a new tab with the same Vue site. Below are the classes defined in ...

Unable to cut a line shape in Three.js using THREE.ExtrudeGeometry for punching

Hey everyone, I'm brand new to Three.js I'm looking to cut out some shapes from a flat board using THREE.ExtrudeGeometry. Check out the code snippet below: // Code snippet here... In my example, I've included a circular shape and t ...

Customize the Angular application based on the geographical location at runtime

Our team has developed a worldwide app that now needs to be customized for specific countries. While some countries can use the existing global components in Angular, others require unique functionality alterations within certain components all while keepi ...

Having trouble parsing JSON data from $_POST while utilizing AngularJS

While working in Angular, I encountered the following scenario: var data = {}; data['name'] = "test"; data['class'] = "testClass"; $http.post('http://testURL',data,function(data){ console.log(data); }); Upon inspecting the ...

Is there a way to add a child to a div with a randomly generated id number?

Don't miss the update at the end! :) I'm developing a small website where users can input data into multiple text boxes, and when they return later, their information is still there (essentially a basic helpdesk system using local storage). The ...

Converting latitude and longitude coordinates to pixels in a 3D environment with the help of three.js

I have geographical coordinates (latitude and longitude) for a specific location on a map. My goal is to represent this point in 3D space using the WebGL library three.js. How can I convert these latitude and longitude coordinates into their respective x ...

Insert a scrollbar into the new popup window on Internet Explorer after the window has been opened

I am looking to enable scrolling in a pop-up window after it has been opened. While FireFox offers the 'window.scrollbars' property for this, Internet Explorer does not have a similar feature. Is there a way to add scrolling functionality in IE u ...

Managing State in React: A Guide to Updating Child Component State from Parent Component

I'm still fairly new to working with React and I'm trying to implement a Bootstrap modal for displaying alert messages. Within my main App.js file, I have an error handler that sends a prop to a Modal.js component in order to trigger the modal t ...

Exploring the wonders of retrieving JSON data in PHP through an Ajax request

A front-end developer is sending an array of data formatted as a JSON object using an Ajax call. The JSON object structure is shown below: { "name": " Test Name ", "image_url": "test URL", "include": [ "1" ], "dimension": [ null ], "media_type" ...

Tips for capturing a webpage thumbnail using a combination of jQuery and PHP from a specified link

Is there a way to capture a web page thumbnail using jQuery and PHP for a specific link? Imagine if I were to assign a PHP variable like this: $screen="http://www.yahoo.com" Can we implement the use of AJAX, jQuery, and PHP to display a thumbnail of the ...

Leveraging ReactJS with Environmental Variables

Seeking answers about React. I am looking for a way to store URL information globally and differentiate between different environments (dev, production etc...). After researching online, I found that the common method is to use .env files which are suppor ...

tips on launching a pre-existing react native project

Trying to run a project downloaded from someone else can be quite challenging. I encountered some issues where the project just wouldn't start, and now I'm completely stuck. Can anyone help me out? https://github.com/sunlight3d/react_native_v0.4 ...