Angular - 如何使选项字段(使用 ng-repeat)取决于先前在选项字段中选择的值?

Angular - how to make a an option field (with ng-repeat) depend on previously chosen value in option field?

我有 3 个字段。 第一个 - 选项字段/ng-repeat over available dates 第二 - 选项字段/根据用户选择的日期,我对数量进行 ng-repeat。我已经尝试了所有不同的方法,但我不能让它依赖于第一个选项字段或其他东西不起作用。任何帮助都会很棒!谢谢!!

html:

<div class="containerDiv">
        <div>
            <select ng-model='date'>
                <option ng-repeat="availableDateProduct in product " value='{{i}}'>{{availableDateProduct.dateOfActivity}}
                </option>
            </select>
        </div>

        <div ng-repeat="availableDateProduct in product ">
            <select>
                <option ng-repeat='i in quantityLister(availableDateProduct.quantity)' value='{{i}}'>
                    {{i}}
                </option>
            </select>
        </div>
        <div>
            <button>Book</button>
        </div>
    </div>

js:

    app.controller('ProductCtrl', function($scope, ProductsFactory, $stateParams) {

        ProductsFactory.fetchByTitle($stateParams.title)
            .then(function(product) {
                $scope.product = product;
            })
        $scope.quantityLister = function(num) {
            var array = [];
            for (var i = 1; i <= num; i++) {
                array.push(i)
            }
            return array;
        }
    })

数据:

var products = [
  {
    title:'Bowling',
    description:'Its fun!',
    photoUrl:'https://www.1.jpg',
    quantity:12,
    price:9,
    dateOfActivity: '2017-13-07'
  },
...
]

谢谢!!

Angular 有一个专门用于完成此任务的指令; ng-options.

首先,我们在控制器中定义一个对象,它将保存从下拉列表中选择的值:

$scope.reservation = {};

接下来,我们在下拉菜单中使用 ng-options,并使用 ng-model 属性 接受选择的值。在第一个下拉列表中,我们获取 products 的数组,显示每个产品的 dateOfActivity,并在选择时将 product 对象保存到 ng-model。 (在 ng-options 定义中从右到左工作)。

ng-model="reservation.selectedProduct"  
ng-options="product as product.dateOfActivity for product in products"

在我们的第二个下拉列表中,您定义了一个函数来获取一个数字并将其散布到一个数组中。我们从reservation.selectedProduct.quantity调用这个函数,然后用这个数组作为ng-options:

的基础
ng-model="reservation.selectedQuantity" 
ng-options="num for num in quantityLister(reservation.selectedProduct.quantity)"

现在我们有一个对象,它具有两个下拉列表的选定值,我们只需要在按下按钮时更改原始数组中的数量。我们还想清除选择后记,以确保用户不会不小心重复预订。

$scope.reserve = function (){
  $scope.reservation.selectedProduct.quantity -= $scope.reservation.selectedQuantity;
  $scope.reservation = {};
};

这里我们用shorthand-=selectedProduct.quantity中减去selectedQuantity。由于 selectedProduct 是双向绑定的,因此对 selectedProduct 的更改也反映在 product 数组中的原始对象中。但是,quantityLister 函数不是动态的;如果我们不重置 $scope.reservation,第二个下拉列表将包含现在无效的可用预订数量。