2016-01-24 65 views
3

我正在使用Angular Formly,並嘗試建立一個選擇字段,允許選擇一個國家的狀態。 第二個字段是一個typeahead字段,允許輸入屬於該狀態的有效區域名稱。 但是,我無法動態更改typeahead選項數組。動態加載formlyhead選項

我已經採取了事先鍵入的內容類型定義從Formly例子,和正常工作與選項的靜態數組:

formlyConfig.setType({ 
    name: 'typeahead', 
    template: '<input type="text" ng-model="model[options.key]" ' + 
     'uib-typeahead="item for item in to.options | filter:$viewValue | limitTo:8" ' + 
     'class="form-control">', 
    wrapper: ['bootstrapLabel', 'bootstrapHasError'], 
}); 

這是我的表單定義:

$scope.selectZoneFormFields = [ 

    { 
    key: 'stateid', 
    type: 'select', 
    templateOptions:{ 
     label: Constants.DIVPOL, 
     valueProp: 'id', 
     labelProp: 'nombre', 
     options: StatesManager.get() 
    } 
    }, 
    { 
    key: 'zoneName', 
    type: 'typeahead', 
    templateOptions: { 
     label: 'Zona', 
     options: $scope.zoneNames 
    } 
    } 
]; 

然後,我看改變狀態和刷新$ scope.zoneNames:

$scope.$watch('geo.stateid', function(newValue, oldValue) { 
    if (newValue === undefined || newValue.length !== 2 || newValue === oldValue) 
    return; 
    console.log(' !!! STATE change detected: ' + oldValue + '-->' + newValue); 
    refreshZones(newValue); 
}); 

問題是,選項typeahead字段保留那些在開始加載(初始值爲$scope.zoneNames

我試圖在formly字段定義中使用控制器,但沒有成功。

想法?

+0

最簡單的方法是使用ExpressionProperties。見下面的答案 – MattE

回答

1
{ 
    key: 'zoneName', 
    type: 'typeahead', 
    templateOptions: { 
     label: 'Zona', 
     options: [] 
    }, 
    expressionProperties: { 
     'templateOptions.options': function($viewValue, $modelValue, $scope){ 
      $scope.to.options = []; //set to an empty array 
      if($scope.model.stateid) { //if the state has been selected 
      $scope.to.options = //whatever code you use to get the zones 
      return $scope.to.options; //return the options 
      }    
     } 
    } 
    }