Javascript ngRepeat breaks指令';s功能
我有两条指令连接在一起(提供了最少的代码示例):Javascript ngRepeat breaks指令';s功能,javascript,angularjs,Javascript,Angularjs,我有两条指令连接在一起(提供了最少的代码示例): 一种是用于验证目的(apValidation) 另一个是可重用的文本字段组件,定义为具有独立作用域的指令,它使用验证指令(apTextField) module.directive('apTextField',function(){ 返回{ 限制:'E', 替换:正确, 范围:{ 名称:“@”, 标签:“@” }, 模板:“{label}}:” } }); 我面临的问题是,当我在ngRepeat上下文中使用文本字段指令时,在这种情况下由模
- 一种是用于验证目的(apValidation)
- 另一个是可重用的文本字段组件,定义为具有独立作用域的指令,它使用验证指令(apTextField)
module.directive('apTextField',function(){ 返回{ 限制:'E', 替换:正确, 范围:{ 名称:“@”, 标签:“@” }, 模板:“{label}}:” } });
<div ng-app="my-app" ng-controller="MainController">
<div>
Without ng-repeat<br>
<div ng-init="field = {name: 'age', label: 'Age'}">
<ap-text-field
label={{field.label}}
name="{{field.name}}">
</ap-text-field>
</div><br>
With ng-repeat<br>
<div ng-repeat="field in fields">
<ap-text-field
label={{field.label}}
name="{{field.name}}">
</ap-text-field>
</div>
</div>
无ng重复
来最好地描述我的问题 原因是,ngRepeat
指令已经编译了它的中继器,并将其从DOM中取出(在$watchCollection()回调期间重新插入);因此,下面的代码var fn=$compile(元素)代码>编译从DOM中提取的元素。因此,解决方案是编译提供给返回回调的新元素
:
compile: function (element) {
element.removeAttr('ap-validation'); // to avoid infinite compilation
element.attr('ng-blur', 'testMe()'); // this method has to be called for the validation to happen
return function (scope, element) {
//^ the new element
$compile(element)(scope);
};
}
演示:
<div ng-app="my-app" ng-controller="MainController">
<div>
Without ng-repeat<br>
<div ng-init="field = {name: 'age', label: 'Age'}">
<ap-text-field
label={{field.label}}
name="{{field.name}}">
</ap-text-field>
</div><br>
With ng-repeat<br>
<div ng-repeat="field in fields">
<ap-text-field
label={{field.label}}
name="{{field.name}}">
</ap-text-field>
</div>
</div>
compile: function (element) {
element.removeAttr('ap-validation'); // to avoid infinite compilation
element.attr('ng-blur', 'testMe()'); // this method has to be called for the validation to happen
return function (scope, element) {
//^ the new element
$compile(element)(scope);
};
}