我正在尝试使用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"
}
}
知道怎么做到这一点?
答案 0 :(得分:4)
您可以在控制器内使用formly built-in watcher或常规$scope.$watch
。
您可以考虑在this cascaded select example中查看后者。
应用于您的模型:
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;
});
}
});
}
}
];