【问题标题】:Angular Formly Nested selects角度形式嵌套选择
【发布时间】:2015-06-09 21:01:48
【问题描述】:

我正在尝试使用 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"
       }
    }

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

【问题讨论】:

    标签: angular-formly


    【解决方案1】:

    您可以在控制器内使用formly built-in watcher 或常规$scope.$watch

    您可以考虑在this cascaded select example 中查看后者。

    应用于您的模型:

    JSBinhttp://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;
                });
              }
            });
    
        }
      }
    ];
    

    【讨论】:

      猜你喜欢
      • 2014-08-18
      • 1970-01-01
      • 2020-09-02
      • 2019-04-02
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多