[英]ngRepeat breaks directive's functionality
我有两个连接在一起的指令(提供了最少的代码示例):
一种是出于验证目的( apValidation )。
module.directive('apValidation', ['$compile', function($compile){ return { restrict: 'A', 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 var fn = $compile(element); return function (scope) { fn(scope); }; }, controller: function ($scope, $attrs) { $scope.testMe = function () { alert("Validating current text field"); }; } } }]);
另一个是可重用的文本字段组件,定义为具有隔离范围的指令,它利用了验证指令( apTextField )。
module.directive('apTextField', function(){ return{ restrict: 'E', replace:true, scope: { name: '@', label: '@' }, template: '<div>{{label}}: <input type="text" id="someId" name="{{name}}" ap-validation></input></div>' } });
我面临的问题是,当我在ngRepeat上下文中使用文本字段指令时,在某种情况下不再调用由模糊事件触发的验证函数。 但是,在ngRepeat上下文之外,验证工作正常。
<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>
我知道ngRepeat会创建一个新的isolatedScope,但是在这种情况下,我无法理解这会如何影响我的指令以及该问题的正确解决方案是什么。
我准备了一个JS小提琴来最好地描述我的问题。
原因是ngRepeat
伪指令已经编译了它的中继器,并且已经将其从DOM中剥离(要在$ watchCollection()回调期间重新插入); 因此,以下代码var fn = $compile(element);
编译从DOM中删除的元素。 因此,解决方案是编译提供给return回调的新element
:
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);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.