4

我在 angular 指令中使用了多个 datepicker,它给了我一个错误 Uncaught Missing instance data for this datepicker因为如果我删除了一个 li 那么它不会在指令中设置 id。

指令.js

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

索引.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>

如何在directive.js 中设置ID?

4

3 回答 3

1

我想您想知道何时可以“获取”(而不是“设置”)指令中的 ID。以下是如何做到这一点:

app.directive('datepicker', function () {
  return {
    link: function($scope, element, attrs) {
      element.bind('focus', function (){
        console.log(attrs.id);
      });
    }
  };
});
于 2013-02-12T16:45:43.010 回答
0

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.

于 2013-02-12T14:03:09.757 回答
0

您应该查看http://docs.angularjs.org/guide/directive#Attributes。在链接阶段,它尚未定义。

另外,我认为您不需要使用 ID 选择器,因为您只需element在链接功能中附加您的事件。

于 2013-02-12T09:28:33.620 回答