AngularJS For Loop with Numbers & Ranges - angularjs

Angular does provide some support for a for loop using numbers within its HTML directives:
<div data-ng-repeat="i in [1,2,3,4,5]">
do something
</div>
But if your scope variable includes a range that has a dynamic number then you will need to create an empty array each time.
In the controller
var range = [];
for(var i=0;i<total;i++) {
range.push(i);
}
$scope.range = range;
In the HTML
<div data-ng-repeat="i in range">
do something
</div>
This works, but it is unnecessary since we won't be using the range array at all within the loop. Does anyone know of setting a range or a regular for min/max value?
Something like:
<div data-ng-repeat="i in 1 .. 100">
do something
</div>

I tweaked this answer a bit and came up with this fiddle.
Filter defined as:
var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=0; i<total; i++) {
input.push(i);
}
return input;
};
});
With the repeat used like this:
<div ng-repeat="n in [] | range:100">
do something
</div>

I came up with an even simpler version, for creating a range between two defined numbers, eg. 5 to 15
See demo on JSFiddle
HTML:
<ul>
<li ng-repeat="n in range(5,15)">Number {{n}}</li>
</ul>
Controller:
$scope.range = function(min, max, step) {
step = step || 1;
var input = [];
for (var i = min; i <= max; i += step) {
input.push(i);
}
return input;
};

Nothing but plain Javascript (you don't even need a controller):
<div ng-repeat="n in [].constructor(10) track by $index">
{{ $index }}
</div>
Very useful when mockuping

I came up with a slightly different syntax which suits me a little bit more and adds an optional lower bound as well:
myApp.filter('makeRange', function() {
return function(input) {
var lowBound, highBound;
switch (input.length) {
case 1:
lowBound = 0;
highBound = parseInt(input[0]) - 1;
break;
case 2:
lowBound = parseInt(input[0]);
highBound = parseInt(input[1]);
break;
default:
return input;
}
var result = [];
for (var i = lowBound; i <= highBound; i++)
result.push(i);
return result;
};
});
which you can use as
<div ng-repeat="n in [10] | makeRange">Do something 0..9: {{n}}</div>
or
<div ng-repeat="n in [20, 29] | makeRange">Do something 20..29: {{n}}</div>

For those new to angularjs.
The index can be gotten by using $index.
For example:
<div ng-repeat="n in [] | range:10">
do something number {{$index}}
</div>
Which will, when you're using Gloopy's handy filter, print:
do something number 0
do something number 1
do something number 2
do something number 3
do something number 4
do something number 5
do something number 6
do something number 7
do something number 8
do something number 9

A short way of doing this would be to use Underscore.js's _.range() method. :)
http://underscorejs.org/#range
// declare in your controller or wrap _.range in a function that returns a dynamic range.
var range = _.range(1, 11);
// val will be each number in the array not the index.
<div ng-repeat='val in range'>
{{ $index }}: {{ val }}
</div>

I use my custom ng-repeat-range directive:
/**
* Ng-Repeat implementation working with number ranges.
*
* #author Umed Khudoiberdiev
*/
angular.module('commonsMain').directive('ngRepeatRange', ['$compile', function ($compile) {
return {
replace: true,
scope: { from: '=', to: '=', step: '=' },
link: function (scope, element, attrs) {
// returns an array with the range of numbers
// you can use _.range instead if you use underscore
function range(from, to, step) {
var array = [];
while (from + step <= to)
array[array.length] = from += step;
return array;
}
// prepare range options
var from = scope.from || 0;
var step = scope.step || 1;
var to = scope.to || attrs.ngRepeatRange;
// get range of numbers, convert to the string and add ng-repeat
var rangeString = range(from, to + 1, step).join(',');
angular.element(element).attr('ng-repeat', 'n in [' + rangeString + ']');
angular.element(element).removeAttr('ng-repeat-range');
$compile(element)(scope);
}
};
}]);
and html code is
<div ng-repeat-range from="0" to="20" step="5">
Hello 4 times!
</div>
or simply
<div ng-repeat-range from="5" to="10">
Hello 5 times!
</div>
or even simply
<div ng-repeat-range to="3">
Hello 3 times!
</div>
or just
<div ng-repeat-range="7">
Hello 7 times!
</div>

Simplest no code solution was to init an array with the range, and use the $index + however much I want to offset by:
<select ng-init="(_Array = []).length = 5;">
<option ng-repeat="i in _Array track by $index">{{$index+5}}</option>
</select>

Without any change in your controller, you can use this:
ng-repeat="_ in ((_ = []) && (_.length=51) && _) track by $index"
Enjoy!

Method definition
The code below defines a method range() available to the entire scope of your application MyApp. Its behaviour is very similar to the Python range() method.
angular.module('MyApp').run(['$rootScope', function($rootScope) {
$rootScope.range = function(min, max, step) {
// parameters validation for method overloading
if (max == undefined) {
max = min;
min = 0;
}
step = Math.abs(step) || 1;
if (min > max) {
step = -step;
}
// building the array
var output = [];
for (var value=min; value<max; value+=step) {
output.push(value);
}
// returning the generated array
return output;
};
}]);
Usage
With one parameter:
<span ng-repeat="i in range(3)">{{ i }}, </span>
0, 1, 2,
With two parameters:
<span ng-repeat="i in range(1, 5)">{{ i }}, </span>
1, 2, 3, 4,
With three parameters:
<span ng-repeat="i in range(-2, .7, .5)">{{ i }}, </span>
-2, -1.5, -1, -0.5, 0, 0.5,

You can use 'after' or 'before' filters in angular.filter module (https://github.com/a8m/angular-filter)
$scope.list = [1,2,3,4,5,6,7,8,9,10]
HTML:
<li ng-repeat="i in list | after:4">
{{ i }}
</li>
result:
5, 6, 7, 8, 9, 10

Shortest answer: 2 lines of code
JS (in your AngularJS controller)
$scope.range = new Array(MAX_REPEATS); // MAX_REPEATS should be the most repetitions you will ever need in a single ng-repeat
HTML
<div data-ng-repeat="i in range.slice(0,myCount) track by $index"></div>
...where myCount is the number of stars that should appear in this location.
You can use $index for any tracking operations. E.g. if you want to print some mutation on the index, you might put the following in the div:
{{ ($index + 1) * 0.5 }}

Hi you can achieve this using pure html using AngularJS (NO Directive is required!)
<div ng-app="myapp" ng-controller="YourCtrl" ng-init="x=[5];">
<div ng-if="i>0" ng-repeat="i in x">
<!-- this content will repeat for 5 times. -->
<table class="table table-striped">
<tr ng-repeat="person in people">
<td>{{ person.first + ' ' + person.last }}</td>
</tr>
</table>
<p ng-init="x.push(i-1)"></p>
</div>
</div>

Using UnderscoreJS:
angular.module('myModule')
.run(['$rootScope', function($rootScope) { $rootScope.range = _.range; }]);
Applying this to $rootScope makes it available everywhere:
<div ng-repeat="x in range(1,10)">
{{x}}
</div>

Very simple one:
$scope.totalPages = new Array(10);
<div id="pagination">
<a ng-repeat="i in totalPages track by $index">
{{$index+1}}
</a>
</div>

Set Scope in controller
var range = [];
for(var i=20;i<=70;i++) {
range.push(i);
}
$scope.driverAges = range;
Set Repeat in Html Template File
<select type="text" class="form-control" name="driver_age" id="driver_age">
<option ng-repeat="age in driverAges" value="{{age}}">{{age}}</option>
</select>

An improvement to #Mormegil's solution
app.filter('makeRange', function() {
return function(inp) {
var range = [+inp[1] && +inp[0] || 0, +inp[1] || +inp[0]];
var min = Math.min(range[0], range[1]);
var max = Math.max(range[0], range[1]);
var result = [];
for (var i = min; i <= max; i++) result.push(i);
if (range[0] > range[1]) result.reverse();
return result;
};
});
usage
<span ng-repeat="n in [3, -3] | makeRange" ng-bind="n"></span>
3 2 1 0 -1 -2 -3
<span ng-repeat="n in [-3, 3] | makeRange" ng-bind="n"></span>
-3 -2 -1 0 1 2 3
<span ng-repeat="n in [3] | makeRange" ng-bind="n"></span>
0 1 2 3
<span ng-repeat="n in [-3] | makeRange" ng-bind="n"></span>
0 -1 -2 -3

I tried the following and it worked just fine for me:
<md-radio-button ng-repeat="position in formInput.arrayOfChoices.slice(0,6)" value="{{position}}">{{position}}</md-radio-button>
Angular 1.3.6

Late to the party. But i ended up just doing this:
In your controller:
$scope.repeater = function (range) {
var arr = [];
for (var i = 0; i < range; i++) {
arr.push(i);
}
return arr;
}
Html:
<select ng-model="myRange">
<option>3</option>
<option>5</option>
</select>
<div ng-repeat="i in repeater(myRange)"></div>

This is jzm's improved answer (i cannot comment else i would comment her/his answer because s/he included errors).
The function has a start/end range value, so it's more flexible, and... it works. This particular case is for day of month:
$scope.rangeCreator = function (minVal, maxVal) {
var arr = [];
for (var i = minVal; i <= maxVal; i++) {
arr.push(i);
}
return arr;
};
<div class="col-sm-1">
<select ng-model="monthDays">
<option ng-repeat="day in rangeCreator(1,31)">{{day}}</option>
</select>
</div>

<div ng-init="avatars = [{id : 0}]; flag = true ">
<div ng-repeat='data in avatars' ng-if="avatars.length < 10 || flag"
ng-init="avatars.length != 10 ? avatars.push({id : $index+1}) : ''; flag = avatars.length <= 10 ? true : false">
<img ng-src="http://actual-names.com/wp-content/uploads/2016/01/sanskrit-baby-girl-names-400x275.jpg">
</div>
</div>
If you want to achieve this in html without any controller or factory.

I whipped this up and saw it might be useful for some. (Yes, CoffeeScript. Sue me.)
Directive
app.directive 'times', ->
link: (scope, element, attrs) ->
repeater = element.html()
scope.$watch attrs.times, (value) ->
element.html ''
return unless value?
element.html Array(value + 1).join(repeater)
To use:
HTML
<div times="customer.conversations_count">
<i class="icon-picture></i>
</div>
Can this get any simpler?
I'm wary about filters because Angular likes to re-evaluate them for no good reason all the time, and it's a huge bottleneck if you have thousands of them like I do.
This directive will even watch for changes in your model, and update the element accordingly.

Suppose $scope.refernceurl is an array then
for(var i=0; i<$scope.refernceurl.length; i++){
$scope.urls+=$scope.refernceurl[i].link+",";
}

This is the simplest variant:
just use array of integers....
<li ng-repeat="n in [1,2,3,4,5]">test {{n}}</li>

Related

Angular.js : Calculating the total of a list of numbers

I need to have a list of numbers display with the total. When someone enters a new number into an input box, the number will be added to the list displayed and the total will change accordingly.
using angular.js...
While itamar's answer works without any doubt, you can write this like this (a bit cleaner in my opinion) :
Controller
Use reduce for total computation :
$scope.numbers = [1,2,3];
$scope.updateTotal = function () {
$scope.total = numbers.reduce(function (total, number) {
if (number) {
total += number;
}
return total;
}, 0);
};
Markup
<span>{{ total }}</span>
<ul>
<li ng-repeat="number in numbers">
<input type="number" ng-model="number" ng-change="updateTotal()">
</li>
</ul>
Since you know when the total value should get updated, better use ng-change here so the computation is only done when needed.
On a side note, you can use type="number" in the input so only numbers can be entered.
Welcome to StackOverflow - next time please provide some code you wrote yourself. In the meantime - I wrote yours for you :-)
JS in your controller:
$scope.numbers = [1,2,3];
$scope.getTotals = function(){
var total = 0;
total = $scope.numbers.reduce(function(prev, curr) {
return prev + curr;
});
return total;
}
HTML:
<ul>
<li ng-repeat="number in numbers"><input ng-model="number"></li>
<li>{{getTotals()}}</li>
</ul>

How to show element once in ng-repeat

I need to loop through a list order by price and as soon as the price is not there then I show a message with unavailable but I don't want to show it for each empty element. I'm using angular 1.2
<div ng-repeat="item in list | orderBy: 'cost'">
<div ng-if="cost == 0 and not already shown">Sorry the following are unavailable</div>
<div>...my item here...</div>
<div>
You can conditionally display two spans - one if it's 0 (your 'not available' message) and another for anything else.
<ul>
<li ng-repeat="d in newData track by $index">
<span ng-show="d > 0">{{d}}</span>
<span ng-show="d === 0">Not Available</span>
</li>
</ul>
The data can be passed through a function to pull all the 0 after the first one:
$scope.data = [1,2,3,0,1,0,0,1,0,2]
$scope.pullDupes = function(array) {
var newArray = [];
var zero;
for(var i = 0; i < array.length; i++) {
if (array[i] !== 0) {
newArray.push(array[i])
}
if (array[i] === 0 && !zero) {
zero = true;
newArray.push(array[i])
}
}
return newArray;
}
$scope.newData = $scope.pullDupes($scope.data);
Plunker
You can show only the first message see here :
<div ng-repeat="item in list | orderBy: 'cost'">
<div style="color:red" ng-show="item.cost == 0 && $first">Message Goes Here</div>
<hr>
<div>{{item.name}} - Price : {{item.cost}}</div>
</div>
and here is a plunker for it :
http://plnkr.co/edit/RwZPZp9rFIChWxqF71O7?p=preview
also the ng-if you are using it wrong you need to do it like this item.cost for the next time
Cheers !
Here is the best way I could find to get it done.
Markup
<div class="sold-out-message" ng-if="displaySoldOutMessage(item)">Sorry, sold out</div>
Controller
$scope.firstSoldOutItemId = false;
$scope.displaySoldOutMessage = function(item) {
if ( item.cost ) return false;
$scope.firstSoldOutItemId = $scope.firstSoldOutItemId || item.id;
return item.id == $scope.firstSoldOutItemId;
};
You can try to use $scope.$whatch with a boolean variable like this:
<div ng-model="actualItem" ng-repeat="item in list | orderBy: 'cost'">
<div ng-if="cost == 0 && oneMessage == true">Sorry the following are unavailable</div>
<div>...my item here...</div>
<div>
</div>
And in your controller you look at actualItem :
$scope.oneMessage = false;
var cpt = 0; // if 1 so you stop to send message
$scope.$watch('actualItem',function(value){
if(value.cost == 0 && $scope.oneMessage == false && cpt < 1)
// i don't know what is your cost but value is your actual item
{
$scope.oneMessage = true;
cpt++;
}
else if($scope.oneMessage == true)
{
$scope.oneMessage == false;
}
});
I am not sure about this but you can try it. It's certainly not the best way.

Filtering a nested ng-repeat: Hide parents that don't have children

I want to make some kind of project list from a JSON file. The data structure (year, month, project) looks like this:
[{
"name": "2013",
"months": [{
"name": "May 2013",
"projects": [{
"name": "2013-05-09 Project A"
}, {
"name": "2013-05-14 Project B"
}, { ... }]
}, { ... }]
}, { ... }]
I'm displaying all data using a nested ng-repeat and make it searchable by a filter bound to the query from an input box.
<input type="search" ng-model="query" placeholder="Suchen..." />
<div class="year" ng-repeat="year in data | orderBy:'name':true">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.months | orderBy:sortMonth:true">
<h3>{{month.name}}</h3>
<div class="project" ng-repeat="project in month.projects | filter:query | orderBy:'name'">
<p>{{project.name}}</p>
</div>
</div>
</div>
If I type "Project B" now, all the empty parent elements are still visible. How can I hide them? I tried some ng-show tricks, but the main problem seems so be, that I don't have access to any information about the parents filtered state.
Here is a fiddle to demonstrate my problem: http://jsfiddle.net/stekhn/y3ft0cwn/7/
You basically have to filter the months to only keep the ones having at least one filtered project, and you also have to filter the years to only keep those having at least one filtered month.
This can be easily achieved using the following code:
function MainCtrl($scope, $filter) {
$scope.query = '';
$scope.monthHasVisibleProject = function(month) {
return $filter('filter')(month.children, $scope.query).length > 0;
};
$scope.yearHasVisibleMonth = function(year) {
return $filter('filter')(year.children, $scope.monthHasVisibleProject).length > 0;
};
and in the view:
<div class="year" ng-repeat="year in data | filter:yearHasVisibleMonth | orderBy:'name':true">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.children | filter:monthHasVisibleProject | orderBy:sortMonth:true">
This is quite inefficient though, since to know if a year is accepted, you filter all its months, and for each month, you filter all its projects. So, unless the performance is good enough for your amount of data, you should probably apply the same principle but by persisting the accepted/rejected state of each object (project, then month, then year) every time the query is modified.
I think that the best way to go is to implement a custom function in order to update a custom Array with the filtered data whenever the query changes. Like this:
$scope.query = '';
$scope.filteredData= angular.copy($scope.data);
$scope.updateFilteredData = function(newVal){
var filtered = angular.copy($scope.data);
filtered = filtered.map(function(year){
year.children=year.children.map(function(month){
month.children = $filter('filter')(month.children,newVal);
return month;
});
return year;
});
$scope.filteredData = filtered.filter(function(year){
year.children= year.children.filter(function(month){
return month.children.length>0;
});
return year.children.length>0;
});
}
And then your view will look like this:
<input type="search" ng-model="query" ng-change="updateFilteredData(query)"
placeholder="Search..." />
<div class="year" ng-repeat="year in filteredData | orderBy:'name':true">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.children | orderBy:sortMonth:true">
<h3>{{month.name}}</h3>
<div class="project" ng-repeat="project in month.children | orderBy:'name'">
<p>{{project.name}}</p>
</div>
</div>
</div>
Example
Why not a custom $filter for this?
Efficiency: the nature of the $diggest cycle would make it much less efficient. The only problem is that this solution won't be as easy to re-use as a custom $filter would. However, that custom $filter wouldn't be very reusable either, since its logic would be very dependent on this concrete data structure.
IE8 Support
If you need this to work on IE8 you will have to either use jQuery to replace the filter and map functions or to ensure that those functions are defined, like this:
(BTW: if you need IE8 support there is absolutely nothing wrong with using jQuery for these kind of things.)
filter:
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
'use strict';
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
map
if (!Array.prototype.map) {
Array.prototype.map = function(callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
}
A = new Array(len);
k = 0;
while(k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[ k ];
mappedValue = callback.call(T, kValue, k, O);
A[ k ] = mappedValue;
}
k++;
}
return A;
};
}
Acknowledgement
I want to thank JB Nizet for his feedback.
For those who are interested: Yesterday I found another approach for solving this problem, which strikes me as rather inefficient. The functions gets called for every child again while typing the query. Not nearly as nice as Josep's solution.
function MainCtrl($scope) {
$scope.query = '';
$scope.searchString = function () {
return function (item) {
var string = JSON.stringify(item).toLowerCase();
var words = $scope.query.toLowerCase();
if (words) {
var filterBy = words.split(/\s+/);
if (!filterBy.length) {
return true;
}
} else {
return true;
}
return filterBy.every(function (word) {
var exists = string.indexOf(word);
if(exists !== -1){
return true;
}
});
};
};
};
And in the view:
<div class="year" ng-repeat="year in data | filter:searchString() | orderBy:'name':true">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.children | filter:searchString() | orderBy:sortMonth:true">
<h3>{{month.name}}</h3>
<div class="project" ng-repeat="project in month.children | filter:searchString() | orderBy:'name'">
<p>{{project.name}}</p>
</div>
</div>
</div>
Here is the fiddle: http://jsfiddle.net/stekhn/stv55sxg/1/
Doesn't this work? Using a filtered variable and checking the length of it..
<input type="search" ng-model="query" placeholder="Suchen..." />
<div class="year" ng-repeat="year in data | orderBy:'name':true" ng-show="filtered.length != 0">
<h1>{{year.name}}</h1>
<div class="month" ng-repeat="month in year.months | orderBy:sortMonth:true">
<h3>{{month.name}}</h3>
<div class="project" ng-repeat="project in filtered = (month.projects | filter:query) | orderBy:'name'">
<p>{{project.name}}</p>
</div>
</div>
</div>

ng-repeat on multiple arrays

Is there a way to loop through multiple arrays in an ng-repeat directive ?
I tried something like
<ul>
<li ng-repeat="sale in randomSales" ng-repeat="image in imageUrls">
<div display-sale></div>
</li>
</ul>
or
<ul>
<li ng-repeat="sale in randomSales, image in imageUrls">
<div display-sale></div>
</li>
</ul>
but it's not working.
I could solve this issue another way, but I'd like to know if this is possible !
EDIT :
Here is my controller & directive :
app.controller('RandomController', ['$rootScope', '$scope',function($rootScope, $scope) {
$scope.randomSales=[];
$scope.imageUrls = [];
for(var i= 0; i < displayrandomSalesNumber ; i++){
var randomNumber = Math.floor((Math.random() * $rootScope.sales.length-1) + 1);
$scope.randomSales.push($rootScope.sales[randomNumber]);
$scope.imageUrls.push($rootScope.sales[randomNumber].image_urls["300x280"][0].url);
}
console.log($scope.randomSales);
}])
.directive('displaySale', function() {
return {
template: '<div class="center"><a href="#/sale/{{sale.store}}/{{sale.sale_key}}">' +
'<header><h2>{{sale.name}}</h2><h4>in {{sale.store}}</h4></header>' +
'<article>' +
'<p>From : {{sale.begins}} To : {{sale.ends}}</p>' +
'<p class="center"><img ng-src="{{image}}"/></p>' +
'<p>{{sale.description}}</p>' +
'</article>' +
'</a></div>'
};
});
the image is already inside $scope.randomSales, I could access it with {{sale.image_urls["300x280"][0].url}} but i'd get a parse error.
to make it work you can try to do following:
- merge 2 arrays to one arrays of objects representing imageUrls and randomSales.
- iterate though them in your template.
For example:
var maxArrayLength = Math.max(randomSales.length, imageUrls.length);
var i = 0;
var result = []; //will put items {sale: ..., image}
for (i =0; i < maxArrayLength; i++){
var currentSale = randomSales[i] != null ? randomSales[i] : null;
var currentImage = imageUrls[i] != null ? imageUrls[i] : null;
result.push({sale: currentSale, image: currentImage})
}
return result;
And them you can use this array to iterate through on your angular template.
The First Solution proposed by you is wrong , we cant have two ng-repeat attributes in one Html tag, I am not sure about the second one . But you could try like this ..i think it would work.
<ul>
<li ng-repeat="sale in randomSales">
<span ng-repeat="image in imageUrls">
<div display-sale></div>
</span>
</li>
</ul>

Angular ng-repeat with a specific value [duplicate]

Angular does provide some support for a for loop using numbers within its HTML directives:
<div data-ng-repeat="i in [1,2,3,4,5]">
do something
</div>
But if your scope variable includes a range that has a dynamic number then you will need to create an empty array each time.
In the controller
var range = [];
for(var i=0;i<total;i++) {
range.push(i);
}
$scope.range = range;
In the HTML
<div data-ng-repeat="i in range">
do something
</div>
This works, but it is unnecessary since we won't be using the range array at all within the loop. Does anyone know of setting a range or a regular for min/max value?
Something like:
<div data-ng-repeat="i in 1 .. 100">
do something
</div>
I tweaked this answer a bit and came up with this fiddle.
Filter defined as:
var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=0; i<total; i++) {
input.push(i);
}
return input;
};
});
With the repeat used like this:
<div ng-repeat="n in [] | range:100">
do something
</div>
I came up with an even simpler version, for creating a range between two defined numbers, eg. 5 to 15
See demo on JSFiddle
HTML:
<ul>
<li ng-repeat="n in range(5,15)">Number {{n}}</li>
</ul>
Controller:
$scope.range = function(min, max, step) {
step = step || 1;
var input = [];
for (var i = min; i <= max; i += step) {
input.push(i);
}
return input;
};
Nothing but plain Javascript (you don't even need a controller):
<div ng-repeat="n in [].constructor(10) track by $index">
{{ $index }}
</div>
Very useful when mockuping
I came up with a slightly different syntax which suits me a little bit more and adds an optional lower bound as well:
myApp.filter('makeRange', function() {
return function(input) {
var lowBound, highBound;
switch (input.length) {
case 1:
lowBound = 0;
highBound = parseInt(input[0]) - 1;
break;
case 2:
lowBound = parseInt(input[0]);
highBound = parseInt(input[1]);
break;
default:
return input;
}
var result = [];
for (var i = lowBound; i <= highBound; i++)
result.push(i);
return result;
};
});
which you can use as
<div ng-repeat="n in [10] | makeRange">Do something 0..9: {{n}}</div>
or
<div ng-repeat="n in [20, 29] | makeRange">Do something 20..29: {{n}}</div>
For those new to angularjs.
The index can be gotten by using $index.
For example:
<div ng-repeat="n in [] | range:10">
do something number {{$index}}
</div>
Which will, when you're using Gloopy's handy filter, print:
do something number 0
do something number 1
do something number 2
do something number 3
do something number 4
do something number 5
do something number 6
do something number 7
do something number 8
do something number 9
A short way of doing this would be to use Underscore.js's _.range() method. :)
http://underscorejs.org/#range
// declare in your controller or wrap _.range in a function that returns a dynamic range.
var range = _.range(1, 11);
// val will be each number in the array not the index.
<div ng-repeat='val in range'>
{{ $index }}: {{ val }}
</div>
I use my custom ng-repeat-range directive:
/**
* Ng-Repeat implementation working with number ranges.
*
* #author Umed Khudoiberdiev
*/
angular.module('commonsMain').directive('ngRepeatRange', ['$compile', function ($compile) {
return {
replace: true,
scope: { from: '=', to: '=', step: '=' },
link: function (scope, element, attrs) {
// returns an array with the range of numbers
// you can use _.range instead if you use underscore
function range(from, to, step) {
var array = [];
while (from + step <= to)
array[array.length] = from += step;
return array;
}
// prepare range options
var from = scope.from || 0;
var step = scope.step || 1;
var to = scope.to || attrs.ngRepeatRange;
// get range of numbers, convert to the string and add ng-repeat
var rangeString = range(from, to + 1, step).join(',');
angular.element(element).attr('ng-repeat', 'n in [' + rangeString + ']');
angular.element(element).removeAttr('ng-repeat-range');
$compile(element)(scope);
}
};
}]);
and html code is
<div ng-repeat-range from="0" to="20" step="5">
Hello 4 times!
</div>
or simply
<div ng-repeat-range from="5" to="10">
Hello 5 times!
</div>
or even simply
<div ng-repeat-range to="3">
Hello 3 times!
</div>
or just
<div ng-repeat-range="7">
Hello 7 times!
</div>
Simplest no code solution was to init an array with the range, and use the $index + however much I want to offset by:
<select ng-init="(_Array = []).length = 5;">
<option ng-repeat="i in _Array track by $index">{{$index+5}}</option>
</select>
Without any change in your controller, you can use this:
ng-repeat="_ in ((_ = []) && (_.length=51) && _) track by $index"
Enjoy!
Method definition
The code below defines a method range() available to the entire scope of your application MyApp. Its behaviour is very similar to the Python range() method.
angular.module('MyApp').run(['$rootScope', function($rootScope) {
$rootScope.range = function(min, max, step) {
// parameters validation for method overloading
if (max == undefined) {
max = min;
min = 0;
}
step = Math.abs(step) || 1;
if (min > max) {
step = -step;
}
// building the array
var output = [];
for (var value=min; value<max; value+=step) {
output.push(value);
}
// returning the generated array
return output;
};
}]);
Usage
With one parameter:
<span ng-repeat="i in range(3)">{{ i }}, </span>
0, 1, 2,
With two parameters:
<span ng-repeat="i in range(1, 5)">{{ i }}, </span>
1, 2, 3, 4,
With three parameters:
<span ng-repeat="i in range(-2, .7, .5)">{{ i }}, </span>
-2, -1.5, -1, -0.5, 0, 0.5,
You can use 'after' or 'before' filters in angular.filter module (https://github.com/a8m/angular-filter)
$scope.list = [1,2,3,4,5,6,7,8,9,10]
HTML:
<li ng-repeat="i in list | after:4">
{{ i }}
</li>
result:
5, 6, 7, 8, 9, 10
Shortest answer: 2 lines of code
JS (in your AngularJS controller)
$scope.range = new Array(MAX_REPEATS); // MAX_REPEATS should be the most repetitions you will ever need in a single ng-repeat
HTML
<div data-ng-repeat="i in range.slice(0,myCount) track by $index"></div>
...where myCount is the number of stars that should appear in this location.
You can use $index for any tracking operations. E.g. if you want to print some mutation on the index, you might put the following in the div:
{{ ($index + 1) * 0.5 }}
Hi you can achieve this using pure html using AngularJS (NO Directive is required!)
<div ng-app="myapp" ng-controller="YourCtrl" ng-init="x=[5];">
<div ng-if="i>0" ng-repeat="i in x">
<!-- this content will repeat for 5 times. -->
<table class="table table-striped">
<tr ng-repeat="person in people">
<td>{{ person.first + ' ' + person.last }}</td>
</tr>
</table>
<p ng-init="x.push(i-1)"></p>
</div>
</div>
Using UnderscoreJS:
angular.module('myModule')
.run(['$rootScope', function($rootScope) { $rootScope.range = _.range; }]);
Applying this to $rootScope makes it available everywhere:
<div ng-repeat="x in range(1,10)">
{{x}}
</div>
Very simple one:
$scope.totalPages = new Array(10);
<div id="pagination">
<a ng-repeat="i in totalPages track by $index">
{{$index+1}}
</a>
</div>
Set Scope in controller
var range = [];
for(var i=20;i<=70;i++) {
range.push(i);
}
$scope.driverAges = range;
Set Repeat in Html Template File
<select type="text" class="form-control" name="driver_age" id="driver_age">
<option ng-repeat="age in driverAges" value="{{age}}">{{age}}</option>
</select>
An improvement to #Mormegil's solution
app.filter('makeRange', function() {
return function(inp) {
var range = [+inp[1] && +inp[0] || 0, +inp[1] || +inp[0]];
var min = Math.min(range[0], range[1]);
var max = Math.max(range[0], range[1]);
var result = [];
for (var i = min; i <= max; i++) result.push(i);
if (range[0] > range[1]) result.reverse();
return result;
};
});
usage
<span ng-repeat="n in [3, -3] | makeRange" ng-bind="n"></span>
3 2 1 0 -1 -2 -3
<span ng-repeat="n in [-3, 3] | makeRange" ng-bind="n"></span>
-3 -2 -1 0 1 2 3
<span ng-repeat="n in [3] | makeRange" ng-bind="n"></span>
0 1 2 3
<span ng-repeat="n in [-3] | makeRange" ng-bind="n"></span>
0 -1 -2 -3
I tried the following and it worked just fine for me:
<md-radio-button ng-repeat="position in formInput.arrayOfChoices.slice(0,6)" value="{{position}}">{{position}}</md-radio-button>
Angular 1.3.6
Late to the party. But i ended up just doing this:
In your controller:
$scope.repeater = function (range) {
var arr = [];
for (var i = 0; i < range; i++) {
arr.push(i);
}
return arr;
}
Html:
<select ng-model="myRange">
<option>3</option>
<option>5</option>
</select>
<div ng-repeat="i in repeater(myRange)"></div>
This is jzm's improved answer (i cannot comment else i would comment her/his answer because s/he included errors).
The function has a start/end range value, so it's more flexible, and... it works. This particular case is for day of month:
$scope.rangeCreator = function (minVal, maxVal) {
var arr = [];
for (var i = minVal; i <= maxVal; i++) {
arr.push(i);
}
return arr;
};
<div class="col-sm-1">
<select ng-model="monthDays">
<option ng-repeat="day in rangeCreator(1,31)">{{day}}</option>
</select>
</div>
<div ng-init="avatars = [{id : 0}]; flag = true ">
<div ng-repeat='data in avatars' ng-if="avatars.length < 10 || flag"
ng-init="avatars.length != 10 ? avatars.push({id : $index+1}) : ''; flag = avatars.length <= 10 ? true : false">
<img ng-src="http://actual-names.com/wp-content/uploads/2016/01/sanskrit-baby-girl-names-400x275.jpg">
</div>
</div>
If you want to achieve this in html without any controller or factory.
I whipped this up and saw it might be useful for some. (Yes, CoffeeScript. Sue me.)
Directive
app.directive 'times', ->
link: (scope, element, attrs) ->
repeater = element.html()
scope.$watch attrs.times, (value) ->
element.html ''
return unless value?
element.html Array(value + 1).join(repeater)
To use:
HTML
<div times="customer.conversations_count">
<i class="icon-picture></i>
</div>
Can this get any simpler?
I'm wary about filters because Angular likes to re-evaluate them for no good reason all the time, and it's a huge bottleneck if you have thousands of them like I do.
This directive will even watch for changes in your model, and update the element accordingly.
Suppose $scope.refernceurl is an array then
for(var i=0; i<$scope.refernceurl.length; i++){
$scope.urls+=$scope.refernceurl[i].link+",";
}
This is the simplest variant:
just use array of integers....
<li ng-repeat="n in [1,2,3,4,5]">test {{n}}</li>

Resources