I have successfully developed a custom directive for a full-page date picker, with some assistance from Stack Overflow. This directive utilizes ngModel to capture the selected date and triggers a callback function that is set when the directive is inserted into the page. However, I encountered an issue where if I include two date pickers on the same page, it always invokes the callback function from the second date picker.
Below is the HTML code snippet...
<fp-date-picker ng-model="dateOne" on-select="dateSelectedOne()"></fp-date-picker>
<fp-date-picker ng-model="dateTwo" on-select="dateSelectedTwo()"></fp-date-picker>
Here's a condensed version of my directive implementation:
angular.module('directives').directive('fpDatePicker', ['$parse', function ($parse) {
return {
restrict: 'EA',
require: 'ngModel',
templateUrl: '/templates/fpDatePicker.tpl.html',
link: function($scope, $element, $attrs, ngModel){
var onSelectCallback = $parse($attrs.onSelect);
$scope.selectedDate = moment();
$scope.selectDate = function(day){
var selectedDay = day.number;
var selectedMonth = $scope.currentMonth.format('MM');
var selectedYear = $scope.currentMonth.format('YYYY');
$scope.selectedDate = moment(selectedYear + '-' + selectedMonth + '-' + selectedDay, 'YYYY-MM-DD');
ngModel.$setViewValue($scope.selectedDate);
onSelectCallback($scope);
};
}
};
}]);
In case needed, here is the template for my directive....
<div class="fpDatePicker-controls">
<a href="#" ng-click="previousMonth()"><</a>
<a href="#" ng-click="nextMonth()">></a>
</div>
<div class="fpDatePicker-month">
<a class="fpDatePicker-day"
ng-repeat="day in currentMonth.days"
ng-click="selectDate(day)"
>
{{day.number}}
</a>
</div>
I initially speculated that the issue might be related to global variables within the link function being shared among all instances of the directive or $attrs not corresponding to the attributes of the specific directive instance. However, after logging $attrs, I confirmed that they were unique for each instance.
I also considered whether making the scope isolated contributed to the problem, but since the callback functions are part of the scope whereas the expression in the attributes is an external attribute, this didn't seem to be the cause.
If anyone could provide insights or solutions, it would be greatly appreciated.
UPDATE: Plunker Demo Available