如何创建一个过滤器,在列出其他对象之前显示一个对象?

How do I create a filter to show one object before listing others?

本文关键字:对象 其他 一个对象 显示 创建 何创建 过滤器 一个      更新时间:2023-09-26

我使用AngularJS来显示来自不同服务器的信息。我想过滤结果,在任何其他类别之前显示"生产"类别。

下面是我的数据结构:

cli: {code: "name",
   development: { type: "development",
                  servers: [array here] },
   production:  { type: "production",
                  servers: [array here] },
   training:    { type: "training",
                  servers: [array here] }
}

我在创建过滤器以首先显示生产服务器时遇到了麻烦,其余部分紧随其后。

我当前的html是

<tr ng-repeat="server in cli | pdFilter">

我已经尝试创建一个过滤器来将生产服务器移到一个数组中,并推动其余部分,但在访问过滤器时,我无法访问客户端对象的子对象。下面是我的代码:

App.filter('pdFilter', [function () {
    return function (cli) {
        // console.log(cli);
        // This outputs a valid object
        if (!angular.isUndefined(cli)) {
            var tempServers = [];
            for(var server in cli) {
                // console.log(cli[server]);
                // This outputs undefined
                if (angular.equals(server.type.substring(0,1), "p")) {
                    tempServers.unshift(server);
                } else {
                    tempServers.push(server);
                }
            }
            return tempServers;
        } else {
            return cli;
        }
    };
}]);

我假设我的问题是当我在cli中循环字段时,但我不确定我的问题在哪里?

谢谢

试试这个,看看是否有效:

app.filter('pdFilter', function() {
    return function( items, condition) {
    condition = condition || "production"        
    var filtered = [];
    if(items === undefined){
      return items;
    }
    angular.forEach(items, function(cli) {          
        if(condition === cli.type){
           filtered.unshift(cli);
        } else {
           filtered.push(cli);   
    });
    return filtered;
  };
});

我给过滤器添加了第二个参数,所以如果以后你需要/想要在不同的条件下过滤,它更容易。然后让HTML看起来像这样:

<tr ng-repeat="server in cli | pdFilter:'production'">

除了这个答案之外,您还可以修改原始对象,使其位于列表的开头,然后在没有过滤器的情况下产生所需的结果。

您应该先放置所有生产服务器,然后再添加其余的

// list of all server types
var types = Object.keys(cli).filter(function(typeName){ return typeof cli[typeName].servers !== 'undefined'; });
// filter production
types.splice(types.indexOf('production'), 1);
// arrays of servers not in production
var arrays = types.map(function(typeName){ return cli[typeName].servers; });
// final result, concat returns new array
return cli.production.concat.apply(this, arrays);