Archna Rangrej
Archna Rangrej

Reputation: 664

Using Multiple Datepicker in Angular directive

I have used multiple datepicker in angular directive and it gives me an error Uncaught Missing instance data for this datepicker because if I removed one li then It doesn't set id in directive.

directive.js

app.directive('datepicker', function () {
  return {
    link: function($scope, element, attrs) {
    setTimeout(function() {
            $("#"+attrs.id).live('focus',function(){
                console.log(attrs.id);
             });
     });
   }
}

index.html

<tr ng-repeat="payment in invoice.payment" id="payment">
    <td>
        <input class="payment_date" id="{{$index}}" placeholder="Payment Date" type="text" ng-model="payment.date" datepicker/>
        <br />
    </td>
</tr>

How can I set ID in the directive.js?

Upvotes: 4

Views: 3151

Answers (3)

Mark Rajcok
Mark Rajcok

Reputation: 364677

I think you want to know when you can "get" (not "set") the ID in the directive. Here's how to do that:

app.directive('datepicker', function () {
  return {
    link: function($scope, element, attrs) {
      element.bind('focus', function (){
        console.log(attrs.id);
      });
    }
  };
});

Upvotes: 1

testing123
testing123

Reputation: 11447

Have you looked at using AngularUI? Then you can use the JQuery passthrough without having to create your own directive (I also added ui-options as an example in case you decide to use it). Here is what it would look like:

<input class="payment_date" ui-jq="datepicker" ui-options="{dateFormat:'dd-mm-yy'}" placeholder="Payment Date" type="text" ng-model="payment.date" />

As for putting an ID on it, I am not sure why you would need one. If you want to get the value of a selected date, instead of doing this:

var myDate = $("#"+myIndex).val();

You should do this:

var myDate = invoice.payment[myIndex].date;

That is the beauty of angular, no need to use the DOM here. Let me know if you have any questions and I will be happy to answer them.

Upvotes: 0

Tosh
Tosh

Reputation: 36030

You should look at http://docs.angularjs.org/guide/directive#Attributes. At the linking phase, it is not defined yet.

Also, I don't think you need to use ID selector, as you simply attach your event against element in your link function.

Upvotes: 0

Related Questions