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

Posted

技术标签:

【中文标题】如何为下拉选择创建指令?【英文标题】:How to create a directive for a dropdown choice? 【发布时间】:2016-07-06 13:00:11 【问题描述】:

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

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

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。此更改还应影响/更新第二个组合 更改第二个组合,更改模型 $scope.mydata.selectedCountry。同样,第一个组合应该受到影响/更新 按下清除按钮应清除两个组合框中的选择(因为清除按钮使模型 $scope.mydata.selectedCountry == null)

我一定是做错了什么,但我找不到。 在这个 plukr 中查看我的示例:http://plnkr.co/edit/oF1R0F1udfiRulx5NvLO?p=preview

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

对此有任何提示吗?

【问题讨论】:

【参考方案1】:

我修改了您的代码,使 &lt;ui-select&gt; 具有 object 字段作为 ng-model 而不是 primitive。在父/子范围的情况下,与原语的 2 路数据绑定可能会出现问题:https://github.com/angular/angular.js/wiki/Understanding-Scopes

所以这里是主要的变化:

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

Plunkr:http://plnkr.co/edit/wCiUoI4aeYPs01FMIVwO

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

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

您的指令模板如下所示:

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

Plunkr:http://plnkr.co/edit/KdgF8U2KqfiqVZS6BS5N

【讨论】:

感谢您的回答。确实,你的笨拙的作品。但是以这种方式工作会限制指令的使用。我想在不同的属性中“存储”国家 uri。例如。 data.birthCountry、data.currentStayCountry 等。我不认为有 2 个指令会是一个很好的解决方案,不是吗?

以上是关于如何为下拉选择创建指令?的主要内容,如果未能解决你的问题,请参考以下文章

如何为 ui-bootstrap 日期选择器创建 angularJs 包装器指令?

如何为下拉菜单中的下拉菜单和颤动中选择的项目添加不同的文本样式?

如何为chrome浏览器设置socks5代理?

如何为chrome浏览器设置socks5代理

如何为以下问题做出选择语句?

如何为数组中的每个创建一个具有唯一图像和选择器的自定义 UIButton?