【问题标题】:Angular access in controller to ng-model in nested ng-repeat控制器中的角度访问嵌套的 ng-repeat 中的 ng-model
【发布时间】:2017-01-05 16:05:45
【问题描述】:

我在主题中遇到问题。在 ng-model 中使用 $parent 没有帮助。 我想要实现的是 2 个可点击按钮,用于将数量字段值增加和减少 1,并在网站底部显示摘要(每个价格*数量的总和)。

var app = angular.module("mainApp", []);
  app.controller("mainCtrl", function ($scope) {
  
  $scope.list1 = [
    { "uniqueId": "1", "name": "cat1" },
    { "uniqueId": "2", "name": "cat2" } 
  ];
  $scope.list2 = [
    { "uniqueId": "1", "name": "prod1", "price": "10" },
    { "uniqueId": "2", "name": "prod2", "price": "20" },
    { "uniqueId": "3", "name": "prod3", "price": "30" }
  ];
  
  // this one below doesn't work at all
  // $scope.quantity[1] = 1; 
  
  $scope.inc = inc;
    
  function inc(id) {
      console.log(id); //works fine
      // increase of exact quantity
  }
      
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="mainApp">
  <div ng-controller="mainCtrl">
    <table ng-repeat="l1 in list1">
      <tr>
        <td>
          {{l1.name}}
        </td>
      </tr>
      <tr ng-repeat="l2 in list2">
        <td>name: {{l2.name}},</td>
        <td>price: {{l2.price}},</td>
        <td>quantity wanted: <input ng-model="quantity[l2.uniqueId]"><button ng-click="inc(l2.uniqueId)" type="button">+</button></td>
      </tr>
    </table>


    {{quantity}}<!-- sum of all quantities * prices -->


  </div>
  <div>

【问题讨论】:

    标签: angularjs controller nested angularjs-ng-repeat angularjs-ng-model


    【解决方案1】:

    请记住,有多种方法可以解决此类问题,这是我看到的主要路线以及每个步骤的示例:

    • 将您的数量存储在某处并对其进行初始化,例如在您的产品对象中,例如在您的控制器中:

      { "uniqueId": "1", "name": "prod1", "price": "10", quantity : 1 },

    • 通过他的 id 创建一个增加产品数量的函数和另一个减少产品数量的函数,例如在您的控制器中:

      function increaseQuantity(id){ // Get your product in the list with a loop // If the product exists // Increase his quantity } function decreaseQuantity(id){ // Get your product in the list with a loop // If the product exists // Decrease his quantity } $scope.increaseQuantity = increaseQuantity; $scope.decreaseQuantity = decreaseQuantity;

    • 在您的按钮中调用正确的方法,例如在您的视图中:

      <td> quantity wanted: {{l2.quantity}} <button ng-click="increaseQuantity(l2.uniqueId)" type="button">+</button> <button ng-click="decreaseQuantity(l2.uniqueId)" type="button">-</button> </td>

    【讨论】:

      猜你喜欢
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多