2013-11-23 78 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的龙,我没有答案(但我在路上找到了这个问题,所以就是这样) 。