When trying to add a directive to a input with a dynamic id, the link method does not properly bind to the object. Given the following jsfiddle or html:
<div ng-app="myApp" ng-controller="MyCtrl">
<p>Date: <input type="text" id="datepicker-{{id}}" datepicker></p>
</div>
And js:
var module = angular.module('myApp', []);
module.directive('datepicker', function() {
var linker = function(scope, element, attrs) {
element.datepicker();
}
return {
restrict: 'A',
link: linker
}
});
function MyCtrl($scope) {
$scope.id = 7
}
What I see on the console debugger is that when link is called it is showing the id literally as "datepicker-{{id}}" and not "datepicker-7".
Is there a way to force this to happen? A better way to implement this?
Update: Should have clarified. The datepicker shows up when clicked, but clicking on a date does not function. I get the error: "Uncaught Missing instance data for this datepicker"
I believe you need transclude:true
in your directive return object, which tells angular to preprocess the markup for things like {{ }}
bindings.
You also need to wrap the call to datepicker()
in a $timeout
to delay the attempt until the next angular cycle runs, ensuring that the translcuded ID is set in the DOM.
This worked for me in jsfiddle
var module = angular.module('myApp', []);
module.directive('datepicker', function($timeout) {
var linker = function(scope, element, attrs) {
$timeout( function(){
element.datepicker();
});
}
return {
restrict: 'A',
link: linker,
transclude: true
}
});
function MyCtrl($scope) {
$scope.id = 7
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With