Way to ng-repeat defined number of times instead of repeating over array?

前端 未结 26 3700
刺人心
刺人心 2020-11-22 14:53

Is there a way to ng-repeat a defined number of times instead of always having to iterate over an array?

For example, below I want the list item to show

26条回答
  •  青春惊慌失措
    2020-11-22 15:28

    I encountered the same problem and this is what I came out with:

    (function () {
      angular
        .module('app')
        .directive('repeatTimes', repeatTimes);
    
      function repeatTimes ($window, $compile) {
        return { link: link };
    
        function link (scope, element, attrs) {
          var times    = scope.$eval(attrs.repeatTimes),
              template = element.clone().removeAttr('repeat-times');
    
          $window._(times).times(function (i) {
            var _scope = angular.extend(scope.$new(), { '$index': i });
            var html = $compile(template.clone())(_scope);
    
            html.insertBefore(element);
          });
    
          element.remove();
        }
      }
    })();
    

    ... and the html:

    {{ $index }}

    LIVE EXAMPLE

    I used underscore's times function as we where already using it on the project, but you can easily replace that with native code.

提交回复
热议问题