【问题标题】:Angularjs dynamic name of ng-modelng-model的Angularjs动态名称
【发布时间】:2018-01-12 19:02:07
【问题描述】:

我正在使用 AngularJS,并且我使用了 ng-repeat 块。我想使用唯一/动态的ng-model 名称。这段代码的想法是,当我单击按钮时,我会增加文本框的值。调试器中的参数名称是正确的,但值没有改变。下面是我使用的代码,但它不起作用,我找不到原因。谁能帮帮我?

<tr ng-repeat="item in resultShoppingCart track by $index">
   <td class="price" ng-bind="item.unitPrice"><span></span></td>
   <td class="qty">
      <input class="form-control input-sm" type="text" ng-value="item.quantity" ng-model="Qty['{{$index}}']">
      <a href=""><i class="fa fa-plus" ng-click="addQuantity(item.quantity, item.productId, $index)"></i></a> <a href="#"><i class="fa fa-minus"></i></a>
   </td>
   <td class="price" ng-bind="item.price"><span>$99.00</span></td>
   <td class="action"><a ng-click="delete(userId,item.productId)">Delete item</a></td>
</tr>

还有我的控制器。

$scope.addQuantity = function (currentQuantity, productId, i) {          
          $scope["Qty['" + i + "']"] = currentQuantity + 1;
          alert($scope["Qty['" + i + "']"]);          
      }

【问题讨论】:

  • 你不能在控制器中用Qty[$index] 代替$scope.Qty[i] 吗?
  • 我试过了,但它不起作用。这是我发现的唯一方法,以便拥有像这样的 o dynalic ng-model .Qty['1']

标签: html angularjs angularjs-ng-repeat angular-ngmodel


【解决方案1】:

由于'{{$index}}' 表达式的结果将是'{{$index}}' 本身。因此,您必须将表达式更改为Qty[$index],而不是在ng-model 中使用Qty['{{$index}}'],这样插值才能正确评估它。


但我建议使用item.quantity,它最终将是独一无二的。无需维护单独的对象(因此我认为没有任何理由单独保存 Quantity)。

<td class="qty">                            
    <input class="form-control input-sm" type="text" ng-value="item.quantity" ng-model="item.quantity" >
    <a href=""><i class="fa fa-plus" ng-click="addQuantity(item)"></i></a> <a href="#"><i class="fa fa-minus"></i></a>                            
</td>

代码

$scope.addQuantity = function (item) {          
    item.quantity = item.quantity + 1;
}

【讨论】:

  • @Celia 很高兴知道它有帮助,谢谢 ;)
猜你喜欢
  • 2014-04-24
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多