Ricalyn Haboc
Ricalyn Haboc

Reputation: 75

Angular JS object as ng-model attribute name

I'm creating a dynamic angular js application wherein I want to use a textbox as a searchtext for the filter of a table. Here's a preview on what I am doing:

Table with Search

As of now, my code looks like this

<table>
                <thead>
                    <tr class="filterrow">
                        <td data-ng-repeat="col in items.Properties">
                            <input id="{{col.DatabaseColumnName}}" type="text" 
                               data-ng-model="search_{{col.DatabaseColumnName}}"/> 
<!-- Above Here I want to dynamically assign the ng-model based on Databasecolumnname property-->
                        </td>
                    </tr>
                    <tr>
                        <th data-ng-repeat="col in items.Properties">{{col.ColumnTitle}}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr data-ng-repeat="content in items2.Contents | filter: search_{{col.DatabaseColumnName}}: search_{{col.DatabaseColumnName}}">
                        <td data-ng-repeat="col in items.Properties">
                            <a href="#">{{content[col.Databasecolumnname ]}}</a>
                        </td>
                    </tr>
                </tbody>
            </table>

I already tried the approach of using $compile but I wasn't able to implement it. Any ideas in an approach? Thanks!

EDIT: Plnkr - plnkr.co/edit/5LaRYE?p=preview

Upvotes: 1

Views: 612

Answers (1)

PSL
PSL

Reputation: 123739

You can do this by setting a base object for your ng-Models. So in your controller you will have:-

 $scope.search = {}; 

and in your view do:-

 <input ng-attr-id="{{col.DatabaseColumnName}}" type="text" 
                           data-ng-model="search[col.DatabaseColumnName]"/> 

With this your dynamic ng-model will be assigned to the search base object, ex:- if col.DatabaseColumnName is col1 then ngModel would be $scope.search.col1

Upvotes: 2

Related Questions