Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular (directive newbie): How to add date time-picker to ngModel so that it can be validated?

I am very new to Angular and have a specific use case in mind I have a form which has two fields - Name and datetime.

The name is ng-model but datetime is not since it is not part of Angular and is a jquery component

What I want to do?
Here is the plunker = http://plnkr.co/edit/wGrvXAFmPGoYSwh9GfxH?p=preview

a.) I want to associate date to ngModel like ngModel="transaction.date"
b.) validate it as required using Angular way

Something which will look like (much like Angular)

<input type="text" name="transactionDate" ng-model="transaction.date" data-date-format="yyyy-mm-dd hh:ii" required>

Why?
a.) To to things Angular way
b.) It makes model more consistent to test, validate

I asked this question on Stackoverflow and it was recommended to use custom directive, can someone give me direction with example how to do it?

Please guide me further since I am not able to validate it currently

Thank you very much

like image 964
daydreamer Avatar asked May 12 '13 22:05

daydreamer


2 Answers

Based on Ketan's answer, I had to write a new directive and associate the value form jQuery to ng-model, which then is validated with form. The directive looks like

app.directive('dateTime', function(){
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope, element, attrs, ngModel){
      if (!ngModel) {
        console.log('no model, returning');
        return;
      }

      element.bind('blur keyup change', function() {
        console.log('datetime changed: ', $('.form_datetime input').val());
        scope.$apply(read);
      });

      read();

      function read() {
        ngModel.$setViewValue(element.val());
      }
    }
  }
});

The plunker can be found here

like image 93
daydreamer Avatar answered Oct 14 '22 04:10

daydreamer


Assuming you know how to write directives, you need to use the NgModelController inside your directive and use the $setViewValue(value) method. (See example the below page).

http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

This has to be called from your custom Datepicker event which triggers when the user completes the selection.

like image 3
Ketan Avatar answered Oct 14 '22 03:10

Ketan