Select 使用 ng-options AngularJS 中的值选择的下拉菜单

Select dropdown as selected using value in ng-options AngularJS

我正在尝试将 China 设置为选定的国家/地区,但不知何故,如果我这样做,它只会将中国设置为下拉列表 - $scope.countrySelected = $scope.countryList[5];

让我知道是否可以仅通过文本设置值,因为通过服务我得到 China 作为我需要匹配的仅文本。

HTML代码-

<select 
 ng-options="country.c_name for country in countryList track by country.c_id" 
 ng-model="countrySelected">
</select>

脚本代码 -

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

myApp.controller('mainCtrl', function($scope){
  $scope.countryList = [
    {c_id: 1, c_name: 'Iran'},
    {c_id: 2, c_name: 'Iraq'},
    {c_id: 3, c_name: 'Pakistan'},
    {c_id: 4, c_name: 'Somalia'},
    {c_id: 5, c_name: 'Libya'},
    {c_id: 6, c_name: 'China'},
    {c_id: 7, c_name: 'Palestine'}
  ];

  $scope.countrySelected = 'China';
})

工作计划 - http://plnkr.co/edit/6qSvuuOtJHVSoNWah0KR?p=preview

您可以使用 filter 方法,它接受一个 回调 函数作为参数。

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

$scope.countrySelected = $scope.countryList.filter(function(item){
     return item.c_name=='China';
})[0];

Working Plnkr

还有一个方法就是用find的方法。

$scope.countrySelected = $scope.countryList.find(function(item){
     return item.c_name=='China';
});

对于与这些方法不兼容的旧版浏览器,您可以实现自己的过滤方法。

Array.prototype.filter = function(func, thisArg) {
   'use strict';
   if ( ! ((typeof func === 'Function') && this) )
      throw new TypeError();

   var len = this.length >>> 0,
   res = new Array(len), // preallocate array
   c = 0, i = -1;
   if (thisArg === undefined)
      while (++i !== len)
        // checks to see if the key was set
        if (i in this)
           if (func(t[i], i, t))
             res[c++] = t[i];
   else
      while (++i !== len)
         // checks to see if the key was set
         if (i in this)
            if (func.call(thisArg, t[i], i, t))
              res[c++] = t[i];
   res.length = c; // shrink down array to proper size
   return res;
};

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter