gpt4 book ai didi

javascript - 使用 ng-options AngularJS 中的值选择下拉列表

转载 作者:行者123 更新时间:2023-11-29 23:40:08 26 4
gpt4 key购买 nike

我正在尝试将 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

关于javascript - 使用 ng-options AngularJS 中的值选择下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45432421/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com