选择具有最小值的选项

Select option with minimum value

本文关键字:选项 最小值 选择      更新时间:2023-09-26

我有JSON:

[{name:'Mary', phone:'555-9876', age:19, date:'2011-06-12T00:00:00.000Z'},
{name:'John', phone:'555-1212', age:10, date:'2011-06-11T00:00:00.000Z'},
{name:'Mike', phone:'555-4321', age:21, date:'2011-07-13T00:00:00.000Z'},
{name:'Adam', phone:'555-5678', age:35, date:'2011-05-14T00:00:00.000Z'},
{name:'Julie', phone:'555-8765', age:29, date:'2011-06-15T00:00:00.000Z'}]

我应该创建<select>并选择最小年龄的名称。在我的情况下-约翰。

我的控制器:

function Projects ($scope, $http) {
    $scope.rootEntry = [];
    $http.get('/api/...').success(function(root) {
        $scope.rootEntry = root;
        $scope.selectedRoot = $scope.rootEntry[0].name;
    });
}
HTML:

<select ng-options="root.age as root.name for root in rootEntry ng-model="selectedRoot">
</select>

我可以选择第一项- $scope.selectedRoot = $scope.rootEntry[0].name;

如何选择最小年龄?

在您的成功处理程序中,遍历$scope.rootEntry以找到年龄最小的项并将该值赋给$scope.selectedRoot

有几种方法可以做到这一点,您可以从$filter和orderBy开始https://docs.angularjs.org/api/ng/filter/orderBy它应该给你一个按年龄排序的列表在你的ngRepeat或$filterprovider上,然后只抓取第一个元素。

把它弄出来了- http://jsfiddle.net/devitate/LKeQz/

无需任何测试奇特的方式是这样的——不要相信这段代码,尽管

var min = Math.min.apply(null,
   Object.keys($scope.rootEntry).map(function(e) {
        return $scope.rootEntry[e]['age'];
   })
);

或者,一个更容易理解的方式,至少对我来说,只是一个循环,它会像-

 var ages = [];
 angular.forEach( $scope.rootEntry , function(value, key) {
   ages.push(value.age);
 });
 return Math.min(ages);

但是你应该直接使用下划线js -

_.min($scope.rootEntry, function(e){ return e.age; });