简体   繁体   中英

AngularJS ng-repeat with delimiter

trying to build an alphabet menu with delimiter('|') like following

A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z

am I doing the right thing? is there any better way to repeat items with delimiter in angularJS? Please guide me.

<div ng-app="myApp">
  <div ng-controller="myController as vm">
    <span ng-repeat="item in vm.menuItems">
      <a href="#">{{item}}</a>&nbsp;<span ng-if="!$last">|</span>
    </span>
  </div>
</div> 

<script>
  angular.module('myApp',[])
  .controller('myController',function(){
    var vm =this;
    vm.menuItems=[];
    activate();
    function activate(){
     vm.menuItems = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('');
    }
  });
</script>

Plunker link : http://plnkr.co/edit/FJEi8T36KGIx1K0hHrFG

That's not a terrible solution at all! A "cleaner" approach, though, could be to do this with css:

ul.menu li {
  display: inline;
}

.menu li:not(:last-child):after {
   content: " |";
}

And I've changed your template to be

<div ng-app="myApp">
  <ul class="menu" ng-controller="myController as vm">
    <li ng-repeat="item in vm.menuItems">
      <a href="#">{{item}}</a>
    </li>
  </ul>
</div>

It's really up to you as to whether the vertical bar should be in the markup (does it add semantic value?) or in the style (is it a purely visual alteration?).

http://plnkr.co/edit/kwGWBZfeWnuQ2wb4b9Ev?p=preview

I prefer using ng-repeat-start and ng-repeat-end when I need delimiters. That way you are not forced to have an element surrounding both your item and your delimiter. Use an ng-if to remove the last delimiter as you were before. Note that I moved the &nbsp; inside the delimiter so that there is not an &nbsp; trailing your Z (as with yours).

<div ng-controller="myController as vm">
   <a ng-repeat-start="item in vm.menuItems" href="#">{{item}}</a><span ng-repeat-end ng-if="!$last">&nbsp;| </span>
</div>

http://plnkr.co/edit/P3E6c6JkcVAH8Z4IBGme?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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