Pages

Thursday, September 25, 2014

Link jQuery input and Angular

Another excellent tip on linking jQuery and Angular. If you are using various jQuery plugins (like datetimepicker) for the looks, it turns out they don't work with AngularJS bindings out of the box. Fortunately, the link is very simple.

Previously, I've written on how to access the full scope.

Here, I'll describe how to link Bootstrap DateTimePicker to AngularJS model. The documentation for the datetimepicker lists the event and handling of the events. The underlying date used by the picker is a Moment, so to get a formatted string, use .format() on the date property.

One way, but a difficult one, would be to do something along the lines of:

        $('.datetimepicker').datetimepicker(customDateTimePickerOptions)

            .on('dp.change', function(event) {

                var jElement = $(event.currentTarget);

                var element = angular.element(jElement);

                var controller = element.controller();

                var scope = element.scope();

                scope.$apply(function() {

                    scope.model.parameters.validFrom = event.date.format();

                });

 });

However, there we don't know which value to update. The fix, fortunately, is extremely simple:

        $('.datetimepicker').datetimepicker(customDateTimePickerOptions)

            .on('dp.change', function(event) {

                var div = $(event.currentTarget);

                var input = div.find('input');

                input.trigger('input');

        });

All that is required, actually, is to fire an 'input' event because this is what AngularJS expects. That way, you can simply use ng-model to bind the value of the input to the Angular model in HTML.

Source: StackOverflow, as usual.

No comments: