Reputation: 94
There is an AngularJS controller which loads data from my API via GET into the scope. The template shows different input fields if certain conditions apply. After these input fields are shown I would like to execute Javascript code (for example Bootstrap .datepicker()) on these elements.
How can I do this? I need an event like AngularJS is ready rendering the template or something..
Upvotes: 0
Views: 461
Reputation: 3394
This is a demo, but you could use it with other libraries.
var myApp = angular.module('myApp', []);
myApp.directive("datepicker", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, elem, attrs, ngModelCtrl) {
var updateModel = function (dateText) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(dateText);
});
};
/* Your custom Date library */
elem.datepicker({
autoclose: true
}).on('changeDate', function(e){
/* Update the model when the date is changed */
updateModel(e.format());
});
}
}
});
<div ng-app="myApp">
<input type="text" ng-model="datePicker" datepicker />
<span>{{datePicker || "00/00/0000"}}</span>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
Upvotes: 0
Reputation: 483
The best way to do that is to create your own directives (see section Creating a Directive that Manipulates the DOM).
There, on link
method, you can get the element and do what you want. Like:
function myDatePickerDirective() {
function link(scope, element, attrs) {
element.datepicker();
}
return {
link: link
};
}
angular.module('app')
.directive('myDatePicker', myDatePickerDirective);
But you may also find useful the AngularUI lib. It has some useful Bootstrap components.
Upvotes: 3