javascript - Angular JS 从数据中选择菜单,在顶部保留 1 个项目?

标签 javascript json angularjs forms

我有一个世界各国的 ng-repeat 选择菜单,它们的名称和 2 个字母的缩写。

我从 Angular 文档中了解到,您可以在选择菜单 ( https://code.angularjs.org/1.2.26/docs/api/ng/directive/select ) 中的 ng-repeat 之前对 1 个 option 项进行硬编码

因此,我按预期将其用于空值“选择...”菜单项。

其余项目来自 JSON 源,在我的服务中按国家代码按字母顺序排列。

现在我的客户希望将美国置于菜单顶部,因为它最常被选择(以及顶部为 UK 的英国版本)。

如果不重新排序我的 JSON 文件,我怎样才能做到这一点?

最佳答案

您可以在 Angular 中使用 orderBy 过滤器(https://docs.angularjs.org/api/ng/filter/orderBy)

因为 orderBy 只能与谓词函数或表达式一起使用,所以您不能编写自己的比较函数,但您可以通过返回一个位于其他所有值之前的值来强制将 US 或 UK 放在首位。

例如,如果每个国家/地区都有一个 ID,而您有阿富汗 (ID = 1)、阿尔巴尼亚 (ID = 2) ...和美国 (ID = 200) 之类的内容,那么您的谓词可能如下所示:

$scope.predicate = function (country) {
    if (country.Name == 'United States') return -1;
    else return country.ID;
}

然后像这样在 ng-repeat 中使用谓词

ng-repeat="country in countries | orderBy:predicate"

这是有效的,因为(根据文档)

the result of this function will be sorted using the <, =, > operator.

如果您没有 ID,则可以使用使用上述比较运算符排序的任何其他属性强制排序。

关于javascript - Angular JS 从数据中选择菜单,在顶部保留 1 个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401714/

相关文章:

jquery - 完全删除 JSON 中的行

json - 带有 Go Parse Json 响应的 Api 请求

javascript - 使用ajax检索json数据的所有 'data'属性

javascript - 使用 Express 和 Node 将 json 文件发送到 pug 模板

javascript - 如何正确使用Jquery模糊功能

android - 为什么 cordova.file.documentsDirectory 为空?

angularjs - 如何在 Controller Angular js中获取带有索引的数组中的对象

javascript - Angular 全栈 + CORS : XMLHttpRequest cannot load

javascript - 如何在数组中添加一个值?

javascript - sap.m.Table 中是否有多个标题,如 sap.ui.table.Table?