如何将一个ng-model的值与一个ng-repeat的值连接起来

How can I concatinate a ng-model value with a value from a ng-repeat

本文关键字:一个 ng-repeat 起来 连接 ng-model      更新时间:2023-09-26

我想循环遍历从REST服务接收的对象数组,并使用ng-repeat指令创建一个动态表单。

这是我的表单与评级指令(采取的UI引导库)

<form name="categoryRatingFrom" data-ng-submit="updateCategories(catRatings) >
<div data-ng-repeat="cats in categories" class="form-group clearfix">
  <label class="control-label">{{ cats.name }}</label>
    <div class="no-outline"
          data-rating
          data-ng-model=" // Here I want to concatenate {{ cats.id }} with the ng-model name catRatings // "
          data-max="6"
          data-rating-states="ratingOptions.ratingStates"
          data-on-hover="atmosphereRating.onHover(value)"
          data-on-leave="atmosphereRating.onLeave()"></div>
     </div>
<form>

我想使用我提交时传递的对象名称和我的循环/数组中当前对象的ID设置data-ng-model值,但是我似乎无法做到这一点。我是否应该在控制器中使用循环接收对象数组,然后使用ng-repeat中的值设置data-ng模型,在提交表单时不向控制器传递任何信息(参见下面的代码):

// loop through the object adding a ng-model name that we match in our form...
for (var i = 0, l = $scope.categories.length; i < l; i++) {
  $scope.categories[i]['modelId'] = 'catRatings.' + $scope.categories[i].id;
}

我将以下内容添加到我的HTML data-ng-model="cats.modelId",但提交时没有传递给控制器-可以有人帮助我解决方案或给我一个答案,我做错了什么?

ng-model接受一个变量,而不是字符串值。我不知道你到底想做什么,但我认为它会是这样的:

ng-model="catRatings[cats.id]"

但是,我不熟悉该指令,所以我不确定它是否接受ng-model属性。

我创建了一个示例,将在整个帖子中引用。以下变量在作用域中声明如下:

$scope.data = [
  {
    'id' : 0,
    'name' : 'Tim'
  },
  {
    'id' : 1,
    'name' : 'John'
  }
];
$scope.ratings = [ '5 stars', '2 stars' ];

当您将模型设置为'catRatings' + {{ cats.id }}时,这意味着您正在某处声明$scope.catRatings1, $scope.catRatings2等。相反,您应该像下面这样直接绑定category对象。

<label ng-repeat="person in data">
  <input type="text" ng-model="person.name">
  ...
</label>

或绑定到具有相应索引

的数组
<label ng-repeat="person in data">
  ...
  <input type="text" ng-model="ratings[$index]">
</label> 

或使用id…绑定到数组

<label ng-repeat="person in data">
  ...
  <input type="text" ng-model="ratings[person.id]">
</label>