简体   繁体   English

Angular ng-repeat over 指令

[英]Angular ng-repeat over directive

I've got a simple directive我有一个简单的指令

directive('animalCard',function(){
    return {
        restrict:'E',
        template: '<div>time for {{a}}</div>'
    }
});

that I want to iterate over an array我想遍历一个数组

$scope.animals = ['penguins','cows','turtles'];

with HTML使用 HTML

<div ng-repeat="a in animals">
    <animal-card>{{a}}</animal-card>
</div>

inside the curly braces for the template I'm using a as the expression to iterate over, and in this case it makes enough sense to say a in animals.在模板的花括号内,我使用a作为迭代的表达式,在这种情况下,在动物中说 a 就足够了。 But what if I wanted to use this same directive when iterating over something where the variable a wouldn't make sense?但是如果我想在迭代变量a没有意义的东西时使用相同的指令怎么办? Is there a better solution to this other than using some generic interpolatable expression like {{item}} ?除了使用一些通用的可插值表达式(如{{item}}之外,还有更好的解决方案吗?

Seems like your question is more ' What should I call my loop variable?似乎你的问题更多 '我应该怎么称呼我的循环变量? `In the end it really doesn't matter. ``最后真的无所谓。 As long as you (or others looking at your code) understand what it's doing it's fine.只要您(或其他查看您的代码的人)了解它在做什么就可以了。

If you want it to be more semantically readable, then you will need to change the name to something generic: item , data , str , d (for data), i (as i is often used for iterations/loops.如果您希望它在语义上更具可读性,那么您需要将名称更改为通用名称: itemdatastrd (用于数据)、 i (因为 i 通常用于迭代/循环。

You directive is literally incorrect.你的指令字面上不正确。 First of all, to insert something into directive from outside, you need transclude: true .首先,要将某些内容从外部插入指令,您需要transclude: true Second, you must bind your variable a in ng-repeat="a in animals" to scope of directive, so it can understand what you want.其次,您必须将ng-repeat="a in animals"的变量a绑定到指令范围,以便它可以理解您想要什么。
So working directive should look like所以工作指令应该看起来像

directive('animalCard',function(){
return {
    restrict:'E',
    transclude: true,
    scope:{
         a: '@'
    },
    template: '<div><div>time for {{a}}</div><div ng-transclude></div></div>'
    }
});

And the last thing.还有最后一件事。

<div ng-repeat="a in animals">
    <animal-card a="{{a}}">this content will be placed at the end, because of ng-tranclude attr in directive</animal-card>
</div>

Demo演示

Edit oh, i glanced at code and seems misunderstood point of question.编辑哦,我看了一眼代码,似乎误解了问题点。 But naming convention really shouldn't make sense, i usually use item .但是命名约定真的没有意义,我通常使用item But if you want to reuse it for very different object models, you probably should use different directive with additional decoration.但是如果你想将它重用于非常不同的对象模型,你可能应该使用不同的指令和额外的装饰。 And yes, it will be not reusability at this point.是的,在这一点上它不是可重用的。 But for same object models, it's reusable, and you shouldn't meet any problems with naming, as they are same type.但是对于相同的对象模型,它是可重用的,您应该不会遇到任何命名问题,因为它们是相同的类型。 imo海事组织

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM