8

I have the following code...

<div ng-controller="CalendarCtrl">
    <input type="text" ng-model="model.selectedDate" ng-change="onCalendarChange()" id="calendar" />
</div>

<script>
    var app = angular.module("myApp", []);

    app.controller("CalendarCtrl", function($scope) {
        var currentDate = new Date();
        $scope.model = { selectedDate: (currentDate.getMonth() + 1) + "/" + currentDate.getDay() + "/" + currentDate.getFullYear() };
        console.log($scope.model);

        $scope.onCalendarChange = function() {
            console.log(currentDate);
        };
    });

    $(document).ready(function() {
        $("#calendar").datepicker();
    });
</script>

This code appears to work beautifully. The change event is being called and the new selectedDate is displayed correctly.

Yet I keep seeing posts where developers are using all kinds of hoops (mainly directives) to get the datepicker to work in Angular.

Am I missing something here?

Scottie
  • 11,050
  • 19
  • 68
  • 109
  • Directives serve this purpose so they can be reused. Everytime you want to use datepicker in your application, you're going to have to duplicate the controller you just wrote. Bad idea. – Rob Jul 18 '14 at 17:54

1 Answers1

6

Using JQuery like this means that you are not declaratively expressing what your app does in the HTML which is kind of the point of Angular.

From the angular homepage:

AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

Your also going to run into a lot of trouble down the road with code like

$(document).ready(function() { $("#calendar").datepicker(); });

As Angular has no idea when this has finished or what has changed. If you start using stuff like this you will need a strong understanding of how dirty checking and the digest cycle work in Angular.

Your date picker won't play nice with other directives either. For example if you put this in an ng-if and hide and show it then the date picker will not be there anymore.

Have you looked into libraries like Angular UI Bootstrap or Angular Strap. They both provide date pickers that work out of the box with Angular.

rob
  • 17,995
  • 12
  • 69
  • 94
  • Yes, I have. I just wasn't sure why it was such a bad idea. Thanks for the explanation. That makes more sense to me now. – Scottie Jul 18 '14 at 18:50