显示选项中的不同文本

时间:2016-02-18 16:52:45

标签: javascript angularjs drop-down-menu ionic-framework

我有一个包含所有国家/地区及其电话代码的下拉列表。我的下拉空间有限,因此文字必须简短。

当下拉列表打开时,我想显示国家/地区名称和电话代码,但当用户选择一个选项时,我只想在下拉列表中显示电话代码作为所选值。

<select ng-model="country" ng-options="c.phoneNumberCountryCode as (c.countryName + ' (+' + c.phoneNumberCountryCode + ')' ) for c in countriesList">           
</select>

http://jsfiddle.net/0fadq61k/

2 个答案:

答案 0 :(得分:1)

我会将ng-selectedng-click结合起来,以实现这一目标。 ng-click(Angular本身固有的)的问题是,虽然它确实刷新了整个列表,但它不会刷新已经选择的项目。我建议你改变你的设计。您可以做的一件事是使用例如国名的前3个字母或类似的组合。将以下代码放在您的小提琴中以查看示例:

HTML

<div ng-controller="Ctrl">     
     <select ng-model="country" ng-options="c.phoneNumberCountryCode as (c.countryName + ' (+' + c.phoneNumberCountryCode + ')' ) for c in countriesList" ng-selected="onCodeSelected(country)" ng-click="onClick()">           
     </select>
</div>

JS

var app = angular.module('app', []);

function Ctrl($scope) {

  //this should be in a service
  $scope.countriesList = [{
    id: 0,
    countryName: 'Portugal',
    phoneNumberCountryCode: '351'
  }, {
    id: 1,
    countryName: 'Spain',
    phoneNumberCountryCode: '34'
  }, {
    id: 2,
    countryName: 'UK',
    phoneNumberCountryCode: '44'
      }, {
    id: 3,
    countryName: 'Australia',
    phoneNumberCountryCode: '61'
  }]; 

    $scope.onClick = function () {
    //refresh data from service instead of hardcoded like below
        $scope.countriesList[0].countryName = "Portugal";
      $scope.countriesList[1].countryName = "Spain";
      $scope.countriesList[2].countryName = "UK";
      $scope.countriesList[3].countryName = "Australia";
  }

    $scope.onCodeSelected = function(countryCode) {
    if (countryCode) {
     angular.forEach($scope.countriesList, function(value, key) {
        if (value.phoneNumberCountryCode === countryCode) {
            var countryShort = $scope.countriesList[value.id].countryName.substring(0, 3);
            $scope.countriesList[value.id].countryName = countryShort;
        }
      })
    }
  }
}

答案 1 :(得分:0)

你能试试吗,

Uri

和脚本

+ xlim(1, 4) + ylim(2,5)