如何在AngularJs中使用ng-repeat过滤(key,value)?

21 浏览
0 Comments

如何在AngularJs中使用ng-repeat过滤(key,value)?

我想做一些类似于:

        {{k}} {{v.pos}}

AngularJs 部分:

function TestCtrl($scope) 
{
    $scope.items = {
                     'A2F0C7':{'secId':'12345', 'pos':'a20'},
                     'C8B3D1':{'pos':'b10'}
                   };
    $scope.hasSecurityId = function(k,v)
    {
       return v.hasOwnProperty('secId');
    }
}

但不知何故,它显示了所有项目。我如何按(key,value)进行过滤?

admin 更改状态以发布 2023年5月20日
0
0 Comments

我的解决方案是创建自定义过滤器并使用它:\n

app.filter('with', function() {
  return function(items, field) {
        var result = {};
        angular.forEach(items, function(value, key) {
            if (!value.hasOwnProperty(field)) {
                result[key] = value;
            }
        });
        return result;
    };
});

\n在HTML中:\n

 
        {{k}} {{v.pos}}

0
0 Comments

从Angular的API中可以看出,过滤器只能应用于数组而不是对象。

“从数组中选择一部分项并将其作为新数组返回。”

在这里您有两个选择:
1)将$scope.items移动到数组中或 -
2)对ng-repeat项进行预过滤,就像这样:

    {{k}} {{v.pos}}

在控制器中:

$scope.filterSecId = function(items) {
    var result = {};
    angular.forEach(items, function(value, key) {
        if (!value.hasOwnProperty('secId')) {
            result[key] = value;
        }
    });
    return result;
}

jsfiddlehttp://jsfiddle.net/bmleite/WA2BE/

0