简体   繁体   English

ng-repeat具有多个元素

[英]ng-repeat with more than one element

I'm having some trouble relating to the use of ng-repeat with multiple elements. 我在将ng-repeat与多个元素一起使用时遇到一些麻烦。 Consider the following html: 考虑以下html:

<li>
    <a href="/">Link</a>
</li>
<li class="divider-vertical"></li>

I want to repeat that for every link but I can't because the ng-repeat would go on the li, and therefore miss the divider li. 我想对每个链接重复该操作,但我不能,因为ng-repeat会出现在li上,因此错过了除法器li。

Another (somewhat inconclusive) stackoverflow thread had the following directive: 另一个(有点不确定的)stackoverflow线程具有以下指令:

app.directive('dividerVertical', function() {
  return {
    restrict: 'A',
      link: function(scope, element, attrs) {
        element.after('<li class="divider-vertical"></li>');
      }
  }
});

Used like this: 像这样使用:

<li ng-repeat="link in links" divider-vertical>
   <a href="{{ link.path }}">{{ link.name }}</a>
</li>

This gives me the following: 这给了我以下内容:

Link1 Link2 Link3 | | |

Rather than the desired: 而不是所需的:

Link1 | Link2 | Link3

I am not sure if there's something I'm doing wrong there or if the approach is fundamentally wrong. 我不确定那里是否存在我做错的事情,或者方法根本上是错误的。

This feels like it should be very simple to achieve and maybe I've gone off entirely on the wrong path, any pointers would be much appreciated. 感觉这应该很容易实现,也许我完全走错了路,任何指针将不胜感激。

UPDATE : changed $timeout to scope.$evalAsync to ensure no flicker and align it to the angular way. 更新 :将$ timeout更改 scope。$ evalAsync以确保没有闪烁并将其与角度对齐。 see this answer 看到这个答案

ng-repeat hasn't added the element to the dom yet. ng-repeat尚未将元素添加到dom。 Wrapping your append in a timeout will do the trick. 将您的追加包装在超时中将达到目的。

Demo 演示

app.directive('dividerVertical', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
      link: function(scope, element, attrs) {
        //added this since I think this is the actual use case ;)
        if(!scope.$last) {
          scope.$evalAsync(function() {
            element.after('<li class="divider-vertical">|</li>');
          });
        }
      }
  }
}]);

PS: there is nothing special about the $timeout here, setTimeout will work just as well, but I like to keep things consistent with angular world. PS:这里的$ timeout没什么特别的,setTimeout也可以工作,但是我想保持角度与世界一致。

I think the current way to handle this would be using ng-repeat-start and ng-repeat-end. 我认为当前处理此问题的方法是使用ng-repeat-start和ng-repeat-end。 You could also get rid of the divider after the last link by looking at the $last variable from the ngRepeat directive 您还可以通过查看ngRepeat指令中的$ last变量来摆脱最后一个链接之后的分隔线

<li ng-repeat-start="link in links">
  <a href="{{link.path}}">{{link.name}}</a>
</li>
<li ng-if="!$last" class="divider-vertical" ng-repeat-end></li>

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

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