lexeme
lexeme

Reputation: 2973

moment.js is visible only by one of two directives defined in the same file

There are two directives in the same file, both directives depend on moment.js library. When applied the first directive (momentNow) sees the moment function and the other one doesn't (the value is undefined).

Both directives are used inside 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 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 {
            /* params 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 {
            /* params are omitted */
            link: function(scope, element, attrs, ngModel) {

                console.log(moment);

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

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

            }
        }
    };

}());

Upvotes: 0

Views: 36

Answers (1)

Magus
Magus

Reputation: 15124

Rename your variable at this line:

var moment = moment();

You are shadowing moment with your variable.

if you are wondering why the console.log(moment); show undefined, take a look at what is hoisting.

Upvotes: 2

Related Questions