2013-11-23 28 views
1

我有一個指令,我正在使用驗證表單域。我想動態添加驗證與指令。下面是我的指令看起來像:如何使用angularjs指令爲表單驗證動態添加屬性?

app.directive('validatedInput', function($compile) { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      var constraints = { 
       'ng-maxlength' : 10, 
       'data-required': '' 
      } 

      angular.forEach(constraints, function(value, key) { 
       element.attr(key, value); 
      } 

      $compile(element)(scope); 
     } 
    } 
} 

這裏是我的標記:

<input type='number' name='fieldName' ng-model='data.test' validated-input></input> 

所以基本上我想要的是該指令ng-maxlength=10data-required=''添加到我的輸入元素,這樣的驗證可以工作(這是一個微不足道的案例;將來我會計劃使用服務從後端獲取約束對象)。問題是,該指令似乎將屬性添加到DOM,但驗證不起作用。換句話說,如果我使用我的瀏覽器的開發工具檢查HTML,標記看起來是正確的,但功能不存在。有什麼想法嗎?

非常感謝

+2

似乎'$ compile'服務是相關的:http://docs.angularjs.org/api/ng.$compile – Cherniv

+0

我試圖添加'$ compile(element)(scope);'在forEach循環,我得到一個控制檯消息,說'$編譯不是一個函數' – user3025812

+0

'$編譯不是一個函數'很可能是因爲你沒有注入'$ compile'在指令 – charlietfl

回答

0

我只是有一點經驗的角度(〜6周),但我已經看到了關於指令做DOM在角一切都是笨重的福...... NKY雞.. 。

我正在用jQuery(它有零雞funk DOM操作智者)做動態後動態添加ng屬性做一個$編譯(在這種情況下,所以INPUT名稱計算爲蹩腳的bootstrap /我正在使用的角度日期選擇器控制):

//# Hook the .calendars object via the required Angular attributes 
$('I.icon-calendar').each(function (i, obj) { 
    var $s, $p = $(this).parent(); 

    //# Set the ng-click of the .parent button 
    $p.attr('ng-click', "calendars.open($event)"); 

    //# Setup the calendar INPUT 
    $s = $p.siblings('INPUT[datepicker-options]'); 
    $s.attr('is-open', "calendars.isOpen['" + $s.attr('name') + "']"); 

    //# Re-$compile the DOM elements so all of the above added Angular attributes are processed 
    $compile($s.get(0))($scope); 
    $compile($p.get(0))($scope); 
}); 

$編譯需要「注入」(我討厭這個詞,爲什麼我們不能只說「通過」?)到控制器,網HRS歐洲:

myApp.factory("Tools", function ($http, $q, $timeout, $compile) {...} 

唯一的問題我已經這樣了遠遠是一些控件/插件等。在$ compile上添加DOM元素,所以目前我正在摔跤多個日期選擇器UL.dropdown-menu被添加到DOM的龍,我沒有答案(但我在路上找到了這個問題,所以就是這樣) 。