Search code examples
htmlangularjsngmodel

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"

Solution

  • 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]"/