2013-05-13 19 views
2

我有一個控制器AppCtrl作爲Angular指令:如何爲父範圍賦值?

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但由於編譯錯誤而失敗,我該如何實現?

回答

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

怎麼樣,如果我想它是ngModel的一部分?我會做'scope:{ngModel:'='}'和''? – daydreamer 2013-05-13 20:54:45

+0

檢查我上面的編輯。 – Ketan 2013-05-13 21:09:49

+0

謝謝,多數人幫助Ketan – daydreamer 2013-05-13 21:16:59