如何在ng-repeat循环中拼接ng-model名称与指定字符串?
Got it, so you're trying to dynamically set ng-model names by concatenating a string with values from your ng-repeat loop in AngularJS—let's break down how to do this right, because the direct interpolation trick (like ng-model="myModel-{{$index}}") won't work here.
Why Direct Interpolation Fails
AngularJS parses ng-model as a scope expression, not a raw string. Writing ng-model="task-{{$index}}" would make Angular look for a variable named literally task-{{$index}} on your scope, which doesn't exist. Instead, we need to use dynamic object properties to create unique, bindable model names.
The Correct Approach
Here's how to implement this properly:
Initialize a storage object in your controller
First, create an empty object (or array) on your scope to hold all the dynamic models. This lets Angular track each model as a property of the object.app.controller('YourController', function($scope) { // Your existing participants data $scope.participantsData = [/* Your participant objects here */]; // Empty object to store dynamic models $scope.participantModels = {}; });Use dynamic object properties in ng-repeat
In your template, bindng-modelto a dynamic property of theparticipantModelsobject. You can concatenate your desired string with$index(or any property from yourxitem) using bracket notation.Here's how to update your existing code snippet:
<div ng-repeat="x in participantsData"> <div class="panel panel-primary"> <a data-toggle="collapse" href="#collapseThree-{{$index}}" class="collapsed" aria-expanded="false"> <div class="panel-heading"> <h4 class="panel-title"> Task Assigned :{{$index + 1}}<span class="caret"></span> </h4> </div> </a> <div id="collapseThree-{{$index}}" class="panel-collapse collapse" aria-expanded="false"> <div class="panel-body"> <!-- Example input with concatenated model name --> <input type="text" ng-model="participantModels['task_input_' + $index]" placeholder="Enter details for Task {{$index + 1}}"> <!-- If you want to concatenate with a property from your participant data --> <input type="text" ng-model="participantModels['task_for_' + x.id]" placeholder="Enter task for {{x.name}}"> </div> </div> </div> </div>
Accessing the Values Later
Once users enter data, you can access the values directly from the participantModels object in your controller:
// Example: Log the value of the first task input console.log($scope.participantModels.task_input_0); // Example: Loop through all models angular.forEach($scope.participantModels, function(value, key) { console.log(`Model ${key}: ${value}`); });
Alternative: Using an Array
If your $index values are sequential (which they usually are in ng-repeat), you can use an array instead of an object for simpler syntax:
- Controller:
$scope.participantModels = []; - Template:
ng-model="participantModels[$index]"
This works great if you don't need a custom string prefix—just the index to distinguish models.
内容的提问来源于stack exchange,提问作者Nishant Singh

