2017-08-01 174 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瀏覽,看看我的答案。我現在使用過濾方法。 –