Angular directive: How to make assign value to par

2019-07-19 07:39发布

问题:

I have a controller AppCtrl as

scope.transaction = {}

The index looks like

  <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>

and my custom directive looks like

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
        }
      }
  });

I want to assign the date value from my directive to $scope.transaction.date but it is failing as compilation error, how can I achieve this?

回答1:

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

Should be

scope: {
      transactionDate: '='
    },

And

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

Should be

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

Then within your directive you can call scope.transactionDate = myValue;

within scope.$apply();

EDIT: If you want to use ng-model within your directive then you can use

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

And

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

In Html

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