Search code examples
javascriptangularjsangularjs-ng-repeat

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


Solution

  • 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