0

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..

Cœur
39k25 gold badges207 silver badges282 bronze badges
asked Sep 6, 2017 at 14:38

2 Answers 2

3

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.

answered Sep 6, 2017 at 15:00
Sign up to request clarification or add additional context in comments.

Comments

0

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>

answered Sep 6, 2017 at 16:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.