angularjs – 如何为下拉选项创建指令?

前端之家收集整理的这篇文章主要介绍了angularjs – 如何为下拉选项创建指令?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我在我的应用程序中为各个国家/地区使用了相当多的下拉选项(也称为组合框).
为了避免一遍又一遍地重复相同的代码,我想为此创建一个指令.

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

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)

我一定是做错了,但我找不到.
我在这个插件中的例子:http://plnkr.co/edit/oF1R0F1udfiRulx5NvLO?p=preview

请注意,在第一个组合框中进行更改,似乎每个工作正常. (第二次组合更新很好)
一旦我在第二个选择,绑定似乎’打破’

有什么暗示吗?

解决方法

修改了你的代码以使< ui-select>将对象字段作为ng-model而不是基元.在父/子范围情况的情况下,对原语的双向数据绑定可能是有问题的: 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>

普兰克:http://plnkr.co/edit/KdgF8U2KqfiqVZS6BS5N

猜你在找的Angularjs相关文章