in JavaScript

Use ranges with ngRepeat


Angular’s ngRepeat directive provides a simple way to iterate over collections to produce HTML dynamically. You probably know it when you have ever worked with lists or arrays in your Angular app:


However, there is a small drawback when working with ngRepeat: You can only iterate over collections of the current scope. Loop definitions (like a typical for-loop) are not supported. This means you cannot to something like this:

The solution

But there is a simple trick to build a workaround for this. If you use a library like Lodash.js or Underscore.js the trick becomes even more simple: As ngRepeat requires a function on the scope, we just provide such a function!

That’s all we need. If we append Lodash/Underscore to our scope, we can use the library within our partials. This might looks like this:

Keep in mind

With great power comes great responsibility. When we append Lodash/Underscore to the Angular scope, we not only pollute the scope with more functionality, we also put program logic from the controller to the partial. And we shouldn’t do that! A partial should be as easy as possible and all application logic should be in the controller or services. But this is also a trade-off, as this solution might be fine for small and simple problems.

Best regards,