同じファイルには2つのディレクティブがあり、両方のディレクティブはmoment.jsライブラリに依存します。最初の指示文(momentNow)を適用すると、の瞬間はと表示され、もう1つは表示されません(値は未定義)。moment.jsは、同じファイル内に定義された2つのディレクティブのうちの1つによってのみ表示されます。
両方のディレクティブは、同じテンプレート内で使用されています。
テンプレート
<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>
モジュール
;(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();
}
}
};
}());
「瞬間」を「未定義」とする2つの関数のどちらを使用しますか? –
@ GabrielLovetro 'momentThen'関数です。私は少し質問を編集しました。 – lexeme