user3865639
user3865639

Reputation: 15

Use a dynamic value in ng-repeat value

How do I get the values within the object to iterate over based on filterOption? Width or Height? Do I need to bind to a model? Most of the other questions that are anything like this have to do with models.

Goal: ng-repeat="section in prefs.filter.DYNAMIC_VALUE_FROM_filterOption

Doesn't output anything: ng-repeat="section in prefs.filter[0]

Successful but not dynamic - width is hardcoded. ng-repeat="section in prefs.filter.width"

FIDDLE http://jsfiddle.net/xyp6y1ap/2/

JAVASCRIPT

function MainCtrl($scope) {

    $scope.prefs = {
        atts: ['width', 'height'],
        filter: {
            width: ['160', '180', '300', '728'],
            height: ['90', '150', '250', '600'],

        },
        filterOption: 1

    };

}

REPEATER IN HTML

       ng-repeat="section in prefs.filter.DYNAMIC_VALUE"

       ng-repeat="section in prefs.filter.width"

Upvotes: 0

Views: 659

Answers (2)

squiroid
squiroid

Reputation: 14037

You can use key,value pair in ng-repeat like:

<section ng-repeat="item in prefs.filter">
    <section ng-repeat="(key,value) in item">
        {{value}}
    </section>
</section>

http://plnkr.co/edit/IPY2YUWLlquWKI7I5MM2?p=preview

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692191

Just like you would do in JavaScript.

$scope.prefs.filterOption is, I assume, the index in the array $scope.prefs.atts of the attribute that you want to iterate over.

So the name of the attribute is $scope.prefs.atts[$scope.prefs.filterOption].

And the actual array you want to iterateover is thus

$scope.prefs.filter[$scope.prefs.atts[$scope.prefs.filterOption]]

So you want, in your HTML

ng-repeat="section in prefs.filter[prefs.atts[prefs.filterOption]]"

This is extremely convoluted, though. The point of the controller is to provide an easy to use model to the view. Instead of dynamically setting the value of an index, which itself allows accessing the name of an attribute, which itself allows accessing an array of widths or heights, you should simply dynamically set a variable pointing to the array itself.

Upvotes: 3

Related Questions