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