Angularjs 如何为下拉选择创建指令?

Angularjs 如何为下拉选择创建指令?,angularjs,angularjs-directive,angular-ui-select,Angularjs,Angularjs Directive,Angular Ui Select,假设我在应用程序中为国家/地区使用了相当多的下拉选项(也称为组合框)。 为了避免重复相同的代码,我想为此创建一个指令 但是:使用以下指令并不能满足我的所有期望(见下文),而复制粘贴模板确实满足我的所有期望 app.directive('countrydropdown', function($compile) { return { restrict: 'E', //attribute or element scope: { countryUri: '=' }

假设我在应用程序中为国家/地区使用了相当多的下拉选项(也称为组合框)。 为了避免重复相同的代码,我想为此创建一个指令

但是:使用以下指令并不能满足我的所有期望(见下文),而复制粘贴模板确实满足我的所有期望

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>

模型(内部指令):{countryUri}
{{$select.selected.name}
我期望它能做什么:

  • 更改第一个组合,将更改$scope.mydata.selectedCountry的型号。此更改还应影响/更新第二个组合
  • 更改第二个组合,将更改型号$scope.mydata.selectedCountry。在这里,第一个组合也应该受到影响/更新
  • 按clear按钮应清除两个组合框中的选择(因为clear按钮使模型$scope.mydata.selectedCountry==null)
我一定是做错了什么,但我找不到。 在这个plukr中使用我的示例:

请注意,在第一个组合框中进行更改,似乎一切都正常。(第二个组合更新很好) 一旦我在第二个上做了一个选择,绑定似乎“坏了”


有什么提示吗?

我修改了你的代码,使
有一个对象字段作为ng model而不是原语。在父/子作用域情况下,与基元的双向数据绑定可能会出现问题:

以下是主要的变化:

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

普朗克:

编辑: 如果您不想在指令中硬编码“selectedCountry”,可以执行以下操作:

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

指令模板如下所示:

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

...

Plunkr:

谢谢你的回答。事实上,你的扑克牌有效。但这种方式限制了指令的使用。我想在不同的属性中“存储”国家uri。例如data.birthCountry、data.currentStayCountry等。我认为这不是一个很好的解决方案,有两个指令,不是吗?