Len
Len

Reputation: 554

How to add dynamic text in ng-model name

Is it possible to add dynamic text in the ng-model name?

data js

self.Map = [{ Id: 0, Name: 'Map1' }, { Id: 1, Name: 'Map2' }, { Id: 2, Name: 'Map3' }]

html

<div ng-repeat="option in mainCtrl.Map">
    <div style="text-align:left;" class="col-md-6">
        {{option.Name}} Map
    </div>
    <div style="text-align:right;" class="col-md-6">
        <input type="text" id="Is{{option.Name}}" name="Is{{option.Name}}" ng-model="mainCtrl.Is{{option.Name}}"/>
    </div>
</div>

desired output

ng-model="mainCtrl.IsMap1"

Upvotes: 1

Views: 446

Answers (2)

chinshuu
chinshuu

Reputation: 61

Have you tried to add dummy field to your HTML input tag like

<div ng-repeat="option in mainCtrl.Map">
    <div style="text-align:left;" class="col-md-6">
        {{option.Name}} Map
    </div>
    <div style="text-align:right;" class="col-md-6">
        <input type="text" id="Is{{option.Name}}" name="Is{{option.Name}}" ng-model="mainCtrl[this.getAttribute('dummyfield')]" dummyfield="{{option.Name}}Role" />
    </div>
</div>

Upvotes: 0

ddickk
ddickk

Reputation: 26

Refer to https://www.w3schools.com/js/js_objects.asp, you can access object in these 2 way:

objectName.propertyName

objectName["propertyName"]

You may try following way such that angularJs can bind the value you want:

<input type="text" id="Is{{option.Name}}" name="Is{{option.Name}}" ng-model="mainCtrl['Is'+option.Name]"/

Upvotes: 1

Related Questions