4

私のアプリケーションで、国に対してかなりの数のドロップダウン選択肢 (コンボボックス) を使用しているとしましょう。同じコードを何度も繰り返さないようにするために、そのためのディレクティブを作成したいと考えています。

ただし、次のディレクティブを使用しても、私の期待をすべて満たすことはできません (以下を参照)。

app.directive('countrydropdown', function($compile) {
  return {
    restrict: 'E', //attribute or element
    scope: {
      countryUri: '='
    },
    templateUrl: 'countrydropdown.html',
    controller : function($scope) {
      $scope.listItems = [ 
        {name: 'Afghanistan', code: 'AF'},
        {name: 'Åland Islands', code: 'AX'},
        {name: 'Albania', code: 'AL'},
      ];      

私のテンプレートは次のとおりです。

<div>
  model (inside directive): {{countryUri}}

   <ui-select ng-model="countryUri" theme="selectize" >
    <ui-select-match placeholder="Select or search a country in the list...">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="'/api/countries/'+country.code as country in listItems | filter: $select.search">
      <span ng-bind-html="country.name | highlight: $select.search"></span>
      <small ng-bind-html="country.code | highlight: $select.search"></small>
    </ui-select-choices>
  </ui-select>

</div>

私が期待すること:

  • 最初のコンボを変更すると、モデル $scope.mydata.selectedCountry が変更されます。この変更は、2 番目のコンボにも影響/更新する必要があります。
  • 2 番目のコンボを変更すると、モデル $scope.mydata.selectedCountry が変更されます。ここでも、最初のコンボが影響を受ける/更新される必要があります
  • クリア ボタンを押すと、両方のコンボボックスの選択がクリアされます (クリア ボタンによりモデルが $scope.mydata.selectedCountry == null になるため)。

私は何か間違ったことをしているに違いありませんが、それを見つけることができません。この plukr で私の例を参照してください: http://plnkr.co/edit/oF1R0F1udfiRulx5NvLO?p=preview

最初のコンボボックスで変更を行うと、すべてが正常に機能するように見えることに注意してください。(2 番目のコンボは正常に更新されます) 2 番目のコンボを選択すると、バインドが「壊れている」ように見えます

これに関するヒントはありますか?

4

1 に答える 1

0

コードを修正し<ui-select>て、オブジェクトフィールドをプリミティブではなくng-modelとして持つようにしました。親/子スコープの状況の場合、プリミティブへの双方向データバインディングは問題になる可能性があります: https://github.com/angular/angular.js/wiki/Understanding-Scopes

したがって、主な変更点は次のとおりです。

<ui-select ng-model="countryData.selectedCountry"></ui-select>

プランク: http://plnkr.co/edit/wCiUoI4aeYPs01FMIVwO

編集: ディレクティブで「selectedCountry」をハードコーディングしたくない場合は、次のようにします。

<country-dropdown country-data="mydata" field="selectedCountry"></country-dropdown>

ディレクティブ テンプレートは次のようになります。

<ui-select ng-model="countryData[field]">
 ...
</ui-select>

プランク: http://plnkr.co/edit/KdgF8U2KqfiqVZS6BS5N

于 2016-03-19T22:26:39.677 に答える