Angular Formly Nested selects

1.5k views Asked by At

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

There are 1 answers

0
Ben Orozco On BEST ANSWER

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

    }
  }
];