0

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();

            }
        }
    };

}());
lexeme
  • 2,915
  • 10
  • 60
  • 125

1 Answers1

2

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.

Magus
  • 14,796
  • 3
  • 36
  • 51
  • Yes, this is it! How to explain `console.log(moment)` showing **undefined** before the `var moment = moment();` line? – lexeme Sep 04 '17 at 11:59