Search code examples
angularjsdynamicangular-ngmodel

Angular dynamic model naming?


i'm learning angular, so please be gentle ;)

I have a table that is populated with some data. And i would like to add filtering (not angular filter, but data filter) on each column.

The idea for me is to add a text box at the top of each column in the header. Then use those textbox values to create the Filters array in my service when it called the api to get the data.

I currently have:

<tr>
                <th ng-repeat="column in report.Columns" ng-show="column.IsVisible">
                    <span class="sort" ng-click="updateSortOrder($index)" ng-class="{'sort-asc': predicate == $index && !reverse, 'sort-desc':predicate == $index && reverse}">{{ column.DisplayName }}</span>
                    <div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-filter fa-fw"></i></span>
                        <input class="form-control" type="text" placeholder="Search" ng-model="">
                    </div>
                </th>
</tr>

what i'm stuck on, is how to assign the text boxes to the ng-model, naming them dynamically based on the column that they stand in.

I thought about using ng-model="column.ColumnName" - but wont that bind the text boxes to the report.Columns.ColumnName ? i dont want to edit that, i want to create a new var on the scope for each one.

Something like $scope.Filters.-ColumnName-.

And then i would like to loop through each ColumnName on $scope.Filters and use it's value in my filters array on my service call.

I hope this is making sense. If I'm heading down the wrong route to achieve this, please feel free to point me in the right direction, as i said, i've just started learning Angular.

Thanks in advance


Solution

  • This is not angular related specifically it is more of a javascript issue.

    For variable property names you use [] object notation

    <input ng-model="filters[column]"
    

    In controller :

    $scope.filters ={}
    

    If properties aren't already created in the scope object, ng-model will create them automatically when there is any user input