0

我正在尝试使用 Formly 实现一系列嵌套的 SELECT。我的选项如下所示:

$scope.productsList = [{
   name : 'product1',
   options : [
      name : 'option1Product1',
      name : 'option2Product1'
   ]
 },
{
   name : 'product2',
   options : [
      name : 'option1Product2',
      name : 'option2Product2'
   ]  
 }
]

我的第一个选择很简单:

{
   type: 'select',
   key: "product",
   templateOptions: {
      label: 'Product',
      options: $scope.productsList,
      "valueProp": "name",
      "labelProp": "name"
   }
}

但是当用户更改所选产品时,我的第二个选择不会更新其选项:

{
       type: 'select',
       key: "option",
       templateOptions: {
          label: 'option',
          options: $scope.productsList[$scope.model.product].options,
          "valueProp": "name",
          "labelProp": "name"
       }
    }

知道如何实现这一目标吗?

4

1 回答 1

4

您可以使用正式内置的 watcher$scope.$watch控制器内部的常规。

您可以考虑在这个级联选择示例中检查后者。

应用于您的模型:

JSBin:http: //jsbin.com/laguhu/1/

vm.formFields = [
  {
    key: 'product',
    type: 'select',
    templateOptions: {
      label: 'Product',
      options: [],
      valueProp: 'name',
      labelProp: 'name'
    },
    controller: /* @ngInject */ function($scope, DataService) {
      $scope.to.loading = DataService.allProducts().then(function(response){
        // console.log(response);
        $scope.to.options = response;
        // note, the line above is shorthand for:
        // $scope.options.templateOptions.options = data;
        return response;
      });

    }
  },
  {
    key: 'options',
    type: 'select',
    templateOptions: {
      label: 'Options',
      options: [],
      valueProp: 'name',
      labelProp: 'name',
    },
    controller: /* @ngInject */ function($scope, DataService) {
        $scope.$watch('model.product', function (newValue, oldValue, theScope) {
          if(newValue !== oldValue) {
            // logic to reload this select's options asynchronusly based on product's value (newValue)
            console.log('new value is different from old value');
            if($scope.model[$scope.options.key] && oldValue) {
              // reset this select
              $scope.model[$scope.options.key] = '';
            } 
            // Reload options
            $scope.to.loading = DataService.allOptionsByProduct(newValue).then(function (res) {
              $scope.to.options = res;
            });
          }
        });

    }
  }
];
于 2015-06-10T02:32:56.597 回答