How to access arguments in a directive?

I defined a directive like this:

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

What I applied to an element like this:

 <input type="text" date-picker="MM/dd/yyyy" ng-model="clientForm.birthDate" /> 

My directive is triggered when I add a date-picker attribute to an element, but I want to know how to access the attribute value ( MM/dd/yyyy ) inside my JS directive so that I can remove this constant next to $filter , I donโ€™t sure if i have any variable i have access to this.

0
angularjs
Jan 24 '13 at 4:41
source share
2 answers

Just pull it straight from attrs :

 return $filter('date')(modelValue, attrs.datePicker); 



BTW, if the only filter you use is date , then you can directly insert it:

 .directive('datePicker', function (dateFilter) { // Keep all your code, just update this line: return dateFilter(modelValue, attrs.datePicker || 'MM/dd/yyyy'); // etc. } 
+4
Jan 24 '13 at 4:45
source share

You can access it from the attrs argument of the 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() : ""; }); } }; }); 
+1
Jan 24 '13 at 5:40
source share



All Articles