2

我有一个AppCtrl控制器

scope.transaction = {}

索引看起来像

  <div class="control-group">
    <label class="control-label">Date</label>

    <div class="controls">
      <div class="control-group input-append date form_datetime">
        <date-time-picker data-ng-model="transaction.date"></date-time-picker>
      </div>
    </div>
  </div>
  <div class="control-group">
    <label class="control-label">Amount</label>

    <div class="controls">
      <div class="input-append">
        <input type="text" name="transactionAmount" ng-model="transaction.amount" required>
      </div>

我的自定义指令看起来像

angular.module('customDirectives', []).directive('dateTimePicker', function() {
      return {
        restrict: 'E',
        replace: true,
        scope: {
          transaction['date']: '=' # COMPILATION ERROR HERE
        },
        template: '<div class="control-group input-append date form_datetime">'+
          '<input type="text"  readonly data-date-format="yyyy-mm-dd hh:ii" name="transactionDate" ng-model="transaction.date" data-date-time required>'+
          '<span class="add-on"><em class="icon-remove"></em></span>'+
          '<span class="add-on"><em class="icon-th"></em></span>'+
          '</div>',
        link: function(scope, element, attrs, ngModel) {
          var input = element.find('input');

          element.datetimepicker({
            format: "yyyy-mm-ddThh:ii:ssZ",
            showMeridian: true,
            autoclose: true,
            todayBtn: true,
            pickerPosition: 'bottom-left'
          });

          element.bind('blur keyup change', function(){
            console.log('binding element');
            scope.$apply(date);
          });

          function date() {
            console.log('setting date',input.val());
            scope.ngModel = input.val();
          }

          date(); // initialize
        }
      }
  });

我想将指令中的日期值分配给,$scope.transaction.date但由于编译错误而失败,我该如何实现?

4

1 回答 1

6
scope: {
      transaction['date']: '=' # COMPILATION ERROR HERE
    },

应该

scope: {
      transactionDate: '='
    },

<date-time-picker data-ng-model="transaction.date"></date-time-picker>

应该

<date-time-picker transaction-date="transaction.date"></date-time-picker>

然后在您的指令中,您可以调用 scope.transactionDate = myValue;

在范围内。$apply();

编辑:如果你想在你的指令中使用 ng-model 那么你可以使用

....
restrict: 'E',
require: '?ngModel',
....

controller.$setViewValue(value); //this will in directive code where you want set the value of the ng-model bound variable.

在 HTML 中

 <date-time-picker data-ng-model="transaction.date"></date-time-picker>
于 2013-05-13T20:45:45.367 回答