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

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

问题描述

我编写了下面的指令来在 ngRepeat 元素在 UI 上呈现时调用一个函数.

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

指令

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

但是它给出了 $compile 错误.如果我删除了需要的部分,它就可以正常工作.

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

为什么 AngularJS 不能接受require:'ngRepeat'"?帮助将不胜感激.

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

推荐答案

require 用于访问另一个指令的控制器.但是 ng-repeat 没有控制器.查看ng-repeat,代码中甚至没有出现控制器这个词.文档 也没有提到 ng-repeat<的控制器/代码>.

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.

通常,当您使用 require 时,是因为您想调用所需控制器的函数.在您的指令的链接函数中,您添加了参数 ngModel —— 如果控制器存在,它将用控制器填充.但是你永远不会在代码中使用这个 ngModel 参数.在这种情况下,您根本不清楚为什么需要使用 require.

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.

编辑:

进一步审查,也许您试图要求 ng-repeat 因为您的 repeat-done 指令在 ng 的上下文之外不起作用-重复.如果这就是原因,另一种解决方案可能是遍历 DOM,查看 repeat-done 指令的父元素,看看它们是否具有ng-repeat"属性.如果未找到,您的指令可能会引发错误.但这似乎是更多的代码,而投资回报却很少......

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天全站免登陆