I'm trying to do something like this:
<ul>
<li ng-repeat="{{myRepeatExpression}}">{{row.name}}</li>
</ul>
But because the ng-repeat
logic is in the compile state of the directive it treats the {{myRepeatExpression}}
as a normal string instead of a variable. Which doesn't work, obviously.
Is there any workaround for that?
You can only use and expression with ng-repeat
and not an interpolated
value.
Now in order to create a dynamic repeatable list you can try either:
- using a function that returns the list dynamically in the
ng-repeat
- this is potentially more expensive since angular needs to call the function first then determine if the collection has changed when doing a $digest
cycle
$watch
for a particular variable on the scope that trigger a change of the list - potentially more efficient but if your dynamic list depends on more than one variable it can get more verbose and can lead to potential bugs from forgetting to add a new $watch
when a new variable is required
Demo plunker
JS:
app.controller('MainCtrl', function($scope) {
var values1 = [{name:'First'}, {name:'Second'}];
var values2 = [{name:'Third'}, {name:'Fourth'}, {name:'Fifth'}];
//1. function way
$scope.getValues = function(id) {
if(id === 1) {
return values1;
}
if(id === 2) {
return values2;
}
}
//2. watch way
$scope.values = undefined;
$scope.$watch('id', function(newVal) {
$scope.values = $scope.getValues(newVal);
});
});
HTML:
<!-- Here we pass the required value directly to the function -->
<!-- this is not mandatory as you can use other scope variables and/or private variables -->
<ul>
<li ng-repeat="v in getValues(id)">{{v.name}}</li>
</ul>
<!-- Nothing special here, plain old ng-repeat -->
<ul>
<li ng-repeat="v in values">{{v.name}}</li>
</ul>
ng-repeat
only accepts it proprietary expression syntax as in row in rows
, but rows
could be a function or promise in your controller. However you need to watch performance closely as ng-repeat doesn't work well with things that change too often (the dreaded max. 10 iterations error).
You can't use ng-repeat with string/variable that should represent the expression directly, but you can create directive that interpolate/parse this value and pass it to the ng-repeat argument and recompile the element.
app.directive('ngVarRepeat',function($compile){
return {
priority:1001, //must be higher than 1000 (priority of ng-repeat)
compile:function($elm,$attrs){
var expression = $attrs.ngVarRepeat;
$elm.removeAttr('ng-var-repeat'); // remove attribute so we can recompile it later
return function(scope,elm,attrs){
$elm.attr('ng-repeat',scope.$eval(expression));
$compile($elm)(scope);
}
}
}
})
Take a look at this plunker: demo plunker from accepted answer
Also please note, that this approach should cause troubles in nested ng-repeats.