2017-08-01 175 views
2

我想设置China所选择的国家,但不知何故,只在下拉创下了中国,如果我做的一样 - $scope.countrySelected = $scope.countryList[5];选择下拉作为使用NG选项AngularJS值选择

让我知道,如果可能的话通过文本设置价值只有通过服务我得到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'; 
}) 

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

回答

1

您可以使用filter方法,其作为参数回调函数。

filter()方法创建一个新数组,其中所有元素都通过 由所提供的函数实现的测试。

$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

+0

我相信它的ES6方法使应用支持IE9 – Nesh

+0

@Nesh将不能在IE浏览,看看我的答案。我现在使用过滤方法。 –