Reputation: 13
how to pass variable "$scope.dateformat" to "format" in directive.Please let me know if any examples are available or suggested. Please suggest me more examples on this.
$scope.dateformat ="yyyy-mm-dd";
menuModule.directive("datepicker", function(){
return {
restrict: "EAC",
require: "ngModel",
scope: {
"ngModel": "="
},
link: function(scope, elem, attr){
$(elem).datepicker({
format: "yyyy-mm-dd", // Above $scope.dateformat should be
// called here
}).on("changeDate", function(e){
return scope.$apply(function(){
console.log(attr);
return scope.ngModel = e.format();
});
});
return scope.$watch("ngModel", function(newValue){
$(elem).datepicker("update", newValue);
});
}
};
});
Upvotes: 0
Views: 241
Reputation: 407
Directive
scope: {
"format": "="
},
link: function(scope, elem, attr){
$(elem).datepicker({
format: scope.format
})
}
HTML
<datepicker format="dateformat"></datepicker>
Upvotes: 0
Reputation: 5694
You don't have a $scope variable in the global scope (I hope).
If this dataFormat is meant as a global configuration, you could register it in angular as a constant like this:
menuModule.constant('DATE_FORMAT', 'yyyy-mm-dd');
and then inject it in your directive:
menuModule.directive("datepicker", function(DATE_FORMAT){
return {
restrict: "EAC",
require: "ngModel",
scope: {
"ngModel": "="
},
link: function(scope, elem, attr){
$(elem).datepicker({
format: DATE_FORMAT
});
// .. rest is omitted
};
});
If you want the format to be passed to the directive through the attributes (and thus make it available in the scope) you'll add it as a scope binding like this:
menuModule.directive("datepicker", function(){
return {
restrict: "EAC",
require: "ngModel",
scope: {
"ngModel": "=",
"dateFormat": "@"
},
link: function(scope, elem, attr){
$(elem).datepicker({
format: scope.dateFormat
});
// .. rest is omitted
};
});
then whenever you use the directive, you can pass the format like this:
<datepicker date-format="yyyy-mm-dd"></datepicker>
or if it comes from a controller
<datepicker date-format="{{$ctrl.dateFormat}}"></datepicker>
Upvotes: 1