Angular Formly Nested selects

久未见 提交于 2019-12-12 01:25:21

问题


I'm trying to achieve a series of nested SELECT with Formly. My options look like this :

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

My first select is easy :

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

But my second select doesn't get its options updated when the users changes the selected product :

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

Any idea of how to achieve this ?


回答1:


You could use a formly built-in watcher, or a regular $scope.$watch inside the controller.

You might consider checking out the the latter in this cascaded select example.

Applied to your model:

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;
            });
          }
        });

    }
  }
];


来源:https://stackoverflow.com/questions/30742748/angular-formly-nested-selects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!