Reputation: 2860
I have a web page that uses a directive called custom-html
which loads a HTML web url into the page (allowing for sub-templates etc). I have this system configured so that it registers properly with $scope
but I seem to be having issues to get JQuery listeners to work with it.
For instance I have the following at the bottom of one of my templates (where the custom-html tag is used above this point)
$(function() {
$(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
});
The datepicker
never works in the sub-templates I am including via the custom-html
directive though. Does anyone have an idea on how I can remedy this? Below is the directive I am using:
backendApp.directive('customHtml', function($compile, $http){
return {
link: function($scope, element, attrs) {
$http.get(attrs['url']).then(function (result) {
element.html(result.data);
element.replaceWith($compile(element.contents())($scope));
});
}
}
});
Using JQuery 1.11.1 and AngularJS 1.2.22 at the moment. Thanks.
EDIT: My apologies, let me clarify the issue that I am having is that when i click on the .datepicker
fields that are being inserted via the custom-html
directive that it's not working. E.g. it's not opening up the JQuery datepicker as it should be when I click on the input
field. When I do this with the regular HTML (not the custom-html
) it works just fine.
Upvotes: 0
Views: 169
Reputation: 5736
The problem is that you need to run the datepicker() init AFTER the element gets compiled. So you should do it after you replace the actual html. The code you have above runs one time on page load (or wherever it is) and won't create datepickers for html elements created AFTER that point.
backendApp.directive('customHtml', function($compile, $http){
return {
link: function($scope, element, attrs) {
$http.get(attrs['url']).then(function (result) {
element.html(result.data);
element.replaceWith($compile(element.contents())($scope));
// DO DATEPICKER INIT HERE ON NEW ELEMENT
});
}
}
});
The better way to do it is a datepicker directive so you know the datepicker element has been compiled before you init it (in the link function)
backendApp.directive('myDatepicker', function($compile, $http){
return {
link: function($scope, element, attrs) {
// ONLY JOB IS INITING DATE PICKER HERE
}
}
});
Upvotes: 1