Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular and mixing jQuery UI - Why not?

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?

like image 716
Scottie Avatar asked Jul 18 '14 17:07

Scottie


1 Answers

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.

like image 67
rob Avatar answered Oct 01 '22 03:10

rob