Generate ng-model inside ng-repeat

2019-07-17 16:06发布

I have been reading a few topics but couldnt find a solution to this one I am stuck on.

I am trying to add ng-model inside ng-repeat something like this:

<span ng-repeat="list in lists">
         <input type="checkbox" ng-model="formData.checkboxes.{{ list.value }}"> {{ list.number }} {{ list.description }} <br/>
</span>

and the list values are like this:

$scope.lists = [

    {

        value:'value1',
        number: '1',
        description:'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ',    
    },

    {
        value:'value2',
        number: '2',
        description:'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ', 
        },

        {
        value:'value3',
        number: '3',
        description:'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ',            },
    ];

Inside the ng-repeat loop, I want it to build a ng-model like: formData.checkboxes.value1 formData.checkboxes.value2, formData.checkboxes.value3 etc..

Is this possible? When I try the above method nothing shows up. What am I doing wrong here?

2条回答
在下西门庆
2楼-- · 2019-07-17 16:25

Try this solution

<span ng-repeat="list in lists">
         <input type="checkbox" ng-model="formData.checkboxes[list.value]"> {{ list.number }} {{ list.description }} <br/>
</span>
查看更多
Explosion°爆炸
3楼-- · 2019-07-17 16:31

First you should define formData.checkboxes model inside your controller like this:

$scope.formData = {
    checkboxes: {}
};

... and the you can populate it like that:

<span ng-repeat="list in lists">
    <input type="checkbox" ng-model="formData.checkboxes[list.value]"/> 
             {{ list.value }} {{ list.number }} {{ list.description }} <br/>
</span>

Please take a look at this JSFiddle for working example.

查看更多
登录 后发表回答