Scottie Scottie - 1 year ago 121
AngularJS Question

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" />

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

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

$scope.onCalendarChange = function() {

$(document).ready(function() {

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?

rob rob
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download