指令不能'要求:ngRepeat“ [英] directive can not ''require:ngRepeat'

查看:136
本文介绍了指令不能'要求:ngRepeat“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面写指令,使调用函数时 ngRepeat 元素获得的UI渲染。

指令

  directives.directive('repeatDone',函数(){
    返回{
        限制:'A',
        要求:'ngRepeat',
        链接:功能(范围,元素,ATTRS,ngModel){
            如果(范围。$最后一个){
                。范围$的eval(attrs.repeatDone);
            }
        }
    };
});

但它给 $编译错误。
如果我删除要求的一部分,它的工作原理确定。

为什么AngularJS不能接受规定:ngRepeat'?
帮助将AP preciated。


解决方案

要求用于访问另一个指令的控制器

。但 NG-重复没有一个控制器。看看在 NG-重复,字控制器甚至没有出现在code。该文档还没有提到一个控制器为 NG-重复

通常情况下,当你使用要求那是因为你要调用所需的控制器的功能。在您的指令中的链接功能您添加参数 ngModel - 这就是将与控制器进行填充,如果它存在。但你永远不会使用在code此 ngModel 参数。这不是真的不清楚为什么你需要使用要求在所有在这种情况下。

修改

在进一步审查,也许你想要求 NG-重复,因为你的重复-完成指令韩元一个 NG-重复的环境之外'T工作。如果是这样的原因,另一种解决方案可能是遍历DOM看着你的重复-完成指令的父元素,看看他们是否有属性'NG重复。如果没有找到,你可以指令抛出一个错误。但是,这似乎是一个很多code W /投资回报率小...

I write below directive to make call a function when ngRepeat element gets rendered on UI.

Directive

directives.directive('repeatDone', function() {
    return {
        restrict: 'A',
        require: 'ngRepeat',
        link: function(scope, element, attrs, ngModel) {
            if (scope.$last) {
                scope.$eval(attrs.repeatDone);
            }
        }
    };
});

But it is giving $compile error. If I remove require part, it works OK.

Why AngularJS can not accept "require: 'ngRepeat'"? Help would appreciated.

解决方案

require is used for accessing the controller of another directive. But ng-repeat does not have a controller. Take a look at the source for ng-repeat, the word controller doesn't even appear in the code. The documentation also makes no mention of a controller for ng-repeat.

Typically, when you use require it's because you want to call functions of the required controller. In the link function for your directive you've added the argument ngModel -- which is what would be populated with the controller if it existed. But you never use this ngModel argument in the code. It's not really clear why you need to use require at all in this case.

EDIT:

On further review, perhaps you're trying to require ng-repeat because your repeat-done directive won't work outside the context of an ng-repeat. If that's the reason, another solution might be to traverse the DOM looking at the parent elements of your repeat-done directive to see if they have the attribute 'ng-repeat'. If not found, your directive could throw an error. But that seems like a lot more code w/little return on investment...

这篇关于指令不能'要求:ngRepeat“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆