2014-11-05 70 views
0

對於我正在處理的項目,我創建了UI Bootstrap日曆小部件的簡化版本。爲Angular指令創建的元素創建名稱

Plunker of my Simplified Calendar, and how I'm using it, is here.

的UI引導日曆的一個有趣的方面是,儘管它去到input[text],它仍然會產生在$error字典中的date驗證的表單控制器,就好像我已經指定了我的DOM中有input[date]元素。

然而,有很多子捕獲的漁獲。在我的plunker的DOM中馬上會注意到的一件事情是,當給定的日期字段不是實際的日期時,我已經指定了錯誤跨度(嘗試輸入一些荒謬的東西,比如'cat'作爲值!)如果你輸入了一些東西不是日期,那些應該出現,但他們沒有。

我試過幾件事情要暴露標記創建於母公司的名稱字段:

  1. $transclude設置爲false,使得<calendar></calendar>標籤獲得與calendar指令的內容替換模板,並指定name屬性。這個「有效」,除了所述輸入被包裝在具有使用Bootstrap樣式框架來看起來正確的類的跨度中。
  2. 直接創建在calendar指令的輸入域的name屬性與綁定,像這樣*:

    app.directive('mustPrecedeDate', [ function() { return { restrict: 'E', template: '<input type="text" name="{{ someName }}" />', scope: {}, controller: 'calendarCtrl', link: function() {} }; } };

  3. link代碼明確查找輸入那就是calendar生成的標記的孩子,併爲其分配一個name屬性。雙方2和3次失敗,因爲很明顯這不是真正的東西,可以做

這導致了我的問題(我找不到SO疑問的是,發現的來源。):在我可以通過什麼方式獲取輸入元素的名稱,以便將驗證結果報告給$error字典,以便我可以爲用戶提供有用的驗證消息?

*:顯然,'左邊四個空格'的代碼塊在編號列表中表現不好,所以我不得不使用反引號代碼表示法來正確地中間格式化文本。如果我沒有發現SO使用的降價設置中的錯誤,請隨時糾正我的格式。

回答

0

#3的東西需要嘗試有點難!

我能夠通過添加以下代碼到我的鏈接功能讓輸入一個名字:

var inputElement = elem.find('input'); 
inputElement.attr('name', inputName); 

...其中inputName從屬性列表刮掉。通過使用如下的compile函數,我能夠將inputName降至生成的input[text]字段。

app.directive('calendar', [ 
    function() { 
     return { 
      restrict: 'E', 
      transclude: false, 
      scope: {}, 
      template: 
       '<span class="input-group">' 
        + '<input class="form-control" required ' 
         + 'type="text" placeholder="MM/dd/yyyy" ' 
         + 'data-ng-model="dt" data-ng-click="toggle($event)" ' 
         + 'data-ng-change="updateParentProperty()" ' 
         + 'datepicker-popup="MM/dd/yyyy" is-open="isOpen" />' 
        + '<span class="input-group-btn">' 
         + '<button type="button" class="btn btn-default" data-ng-click="toggle($event)">' 
          + '<i class="fa fa-calendar"></i>' 
         + '</button>' 
        + '</span>' 
       + '</span>', 
      controller: 'calendarCtrl', 
      compile: function(elem, attrs) { 
       var inputName = attrs.inputName; 

       var inputElement = elem.find('input'); 
       inputElement.attr('name', inputName); 

       // Compile returns a Link function! 
       return function(scope, elem, attrs, ctrl) { 
        var modelName = attrs.ngModel; 

        scope.parentProperty = modelName; 
        scope.dt = scope.$parent[modelName]; 
       }; 
      } 
     }; 
    } 
]);