AngularJS:如何获取 ng-options 的过滤数组

AngularJS: How to obtain the filtered array of ng-options

本文关键字:ng-options 过滤 数组 获取 何获取 AngularJS      更新时间:2023-09-26

我有一个这样的选择:

<select ng-model="myType"
ng-options="type in types | filter:compatibleTypes">

compatibleType 被定义为控制器$scope函数:

$scope.compatibleTypes = function(item) {
 //Returns true or false
 //depending on another model
}

在控制器中,我需要知道数组"type"的第一个过滤元素(如果有的话)。或者更准确地说,当模型"myType"发生变化时,我必须使用过滤列表的第一个元素设置模型"myType"的值。

filter是一个 Angular 原生过滤器。这意味着它可以注入到许多地方,包括您的控制器:

var myController = ['$scope', 'filterFilter', function ($scope, filterFilter) {
    $scope.compatibleTypes = function(item) {
        //Returns true or false
        //depending on another model
    }
    $scope.filteredResults = filterFilter($scope.types, $scope.compatibleTypes);
}];

将$filter注入控制器

function myCtrl($scope, $filter)
{
}

然后,您只需在控制器中使用过滤器,就不必再在HTML中使用它了!

    $scope.filteredTypes = $filter('filter')(types, $scope.compatibleTypes);

在你的HTML中,你可以使用ng-options="type in filteredTypes"在您的控制器中

$scope.filteredTypes[0] 

得到第一个!