Angualrjs在控制器中过滤数组

时间:2016-04-07 09:45:28

标签: angularjs filter

我有Json样本。我很基于关键价值。

fiter没有排序确切的值

示例:

angular.module('myApp').controller('testController', ['$filter', '$scope',
function($filter, $scope) {

    var obj = '[{"id":"1","m_id":1,"value":"Male"},
                {"id":"2","m_id":1,"value":"Female"},
                {"id":"3","m_id":1,"value":"Other"},
                {"id":"45","m_id":9,"value":"Single"},
                {"id":"46","m_id":9,"value":"Married"},
                {"id":"47","m_id":10,"value":"Father"},
                {"id":"48","m_id":10,"value":"Mother"},
                {"id":"61","m_id":10,"value":"Cousin"},
                {"id":"62","m_id":10,"value":"Other"}]';

    var obj1 = JSON.parse(obj);
    var result = $filter('filter')(obj1, {
        m_id : "1"
    });
}]);

输出:

[{"id":"1","m_id":1,"value":"Male"},
 {"id":"2","m_id":1,"value":"Female"},
 {"id":"3","m_id":1,"value":"Other"},
 {"id":"47","m_id":10,"value":"Father"},
 {"id":"48","m_id":10,"value":"Mother"},
 {"id":"61","m_id":10,"value":"Cousin"},
 {"id":"62","m_id":10,"value":"Other"}]

预期产出:

[{"id":"1","m_id":1,"value":"Male"},
 {"id":"2","m_id":1,"value":"Female"},
 {"id":"3","m_id":1,"value":"Other"}]

Click here

2 个答案:

答案 0 :(得分:3)

您也可以使用Javascript Filter()

这样做
var result = obj1.filter(function(v){
    return v.m_id == 1;
});

DEMO

AngularJS v.1.1.3 中,完全过滤器为provided natively

var result = $filter('filter')(obj1, 
    {m_id : 1},
    true // ==========> this is for exact match
);

Working DEMO

答案 1 :(得分:1)

更改

var result = $filter('filter')(obj1, {
        m_id : "1"
});

var result = $filter('filter')(obj1, function(item) { return item && item.m_id == 1; });

演示here