I've defined a directive like so:
angular.module('MyModule', [])
.directive('datePicker', function($filter) {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$formatters.unshift(function(modelValue) {
console.log('formatting',modelValue,scope,elem,attrs,ctrl);
return $filter('date')(modelValue, 'MM/dd/yyyy');
});
ctrl.$parsers.unshift(function(viewValue) {
console.log('parsing',viewValue);
var date = new Date(viewValue);
return isNaN(date) ? '' : date;
});
}
}
});
Which I apply to an element like so:
<input type="text" date-picker="MM/dd/yyyy" ng-model="clientForm.birthDate" />
My directive gets triggered whenever I add the date-picker attribute to an element, but I want to know how to access the attribute's value (MM/dd/yyyy) inside my directive JS so that I can remove that constant beside $filter. I'm not sure if any of the variables I have access to provide this.
Just pull it directly from the attrs:
return $filter('date')(modelValue, attrs.datePicker);
BTW, if the only filter you're using is date, then you can inject that directly:
.directive('datePicker', function (dateFilter) {
// Keep all your code, just update this line:
return dateFilter(modelValue, attrs.datePicker || 'MM/dd/yyyy');
// etc.
}
You can access it from attrs argument of link function.
Demo: http://plnkr.co/edit/DBs4jX9alyCZXt3LaLnF?p=preview
angModule.directive('moDateInput', function ($window) {
return {
require:'^ngModel',
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
var moment = $window.moment;
var dateFormat = attrs.moMediumDate;
attrs.$observe('moDateInput', function (newValue) {
if (dateFormat == newValue || !ctrl.$modelValue) return;
dateFormat = newValue;
ctrl.$modelValue = new Date(ctrl.$setViewValue);
});
ctrl.$formatters.unshift(function (modelValue) {
scope = scope;
if (!dateFormat || !modelValue) return "";
var retVal = moment(modelValue).format(dateFormat);
return retVal;
});
ctrl.$parsers.unshift(function (viewValue) {
scope = scope;
var date = moment(viewValue, dateFormat);
return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";
});
}
};
});