使用ng-options中先前选择的值

时间:2015-01-01 03:03:39

标签: javascript angularjs

我有以下代码:

<label class="item item-input item-select" name="coffeehouse">
  <span class="input-label">Coffee House</span>
  <select ng-options="shop.label for shop in products" ng-model="order.coffeehouse"></select>
</label>
<label class="item item-input item-select" name="product">
  <span class="input-label">Product</span>
  <select ng-options="product.label for product in //PROBLEM//" ng-model="order.product"></select>
</label>

我需要为第二个选择做的是从$scope.products[order.coffeehouse].products获取产品列表,因此它取决于第一个选择的结果。但是,我找不到任何关于使用范围变量作为ng-options中另一个范围变量的键的文档。

控制器:

.controller('DropCtrl', function($scope, $ionicLoading, Products) {
  $ionicLoading.show({
    template: 'Loading...'
  });
  Products.all(function(products) {
    $scope.products = products;
    $ionicLoading.hide();
  });
})

请注意,它使用了工厂,因此您无法在此处查看数据源,但它是一组对象,如下所示:

[
  { label: 'Store 1', products: [{ label: 'Product 1' }, { label: 'Product 2' }] },
  { label: 'Store 2', products: [{ label: 'Product 1' }, { label: 'Product 2' }] }
]

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

以下是一种方法:

http://jsfiddle.net/4te4x93h/1/

&#13;
&#13;
var myApp = angular.module('myApp', ['ionic']);

myApp.controller('DropCtrl', function($scope, $ionicLoading) {
    $ionicLoading.show({
        template: 'Loading...',
        animation: 'fade-in',
        showBackdrop: true,
        showDelay: 10
    });
    $scope.order = {};
    $scope.products = [
      { label: 'Store 1', products: [{ label: 'Product 1' }, { label: 'Product 2' }] },
      { label: 'Store 2', products: [{ label: 'Product 1' }, { label: 'Product 2' }] }
    ];
    // Mock loading for 1.5 seconds.
    setTimeout(function() {
        $ionicLoading.hide();
    }, 1500);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://code.ionicframework.com/1.0.0-beta.6/js/ionic.bundle.js"></script>
<link href="http://code.ionicframework.com/1.0.0-beta.6/css/ionic.css" rel="stylesheet"/>

<div ng-app="myApp" ng-controller="DropCtrl">
    <label class="item item-input item-select" name="coffeehouse">
        <span class="input-label">Coffee House</span>
        <select ng-options="shop.label for shop in products" ng-model="order.coffeehouse"></select>
    </label>
    <label class="item item-input item-select" name="product">
        <span class="input-label">Product</span>
        <select ng-options="product.label for product in order.coffeehouse.products" ng-model="order.product"></select>
    </label>
    <p ng-bind="order.coffeehouse.label"></p>
    <p ng-bind="order.product.label"></p>
</div>
&#13;
&#13;
&#13;

如果您有//problem//,则只需参考订单对象的咖啡馆财产。

在第一个下拉列表中进行选择之前,第二个下拉列表中没有选项。一旦你将咖啡馆绑定到订单,就会填充第二个下拉菜单。