如何从AngularJS获取过滤后的数据对象?

时间:2013-05-22 04:48:05

标签: angularjs

我无法弄清楚在更改事件发生后我如何接收过滤后的数据。我的代码结构如下所示。警报被解雇,但如何继续前进?

<html ng-app>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>

</head>


<body ng-controller="List">

    Search: <input ng-change="getData()" ng-model="query">
    Search: <select ng-change="getData()" ng-model="query2">
    <option></option>
    <option>Berlin</option>
    <option>Hamburg</option>
</select>
 <div>
    <ul class="names" >
        <li ng-model="item" " ng-repeat="name in names | filter:query | filter:query2">
            {{name.firstname}}, {{name.lastname}}, {{name.age}}, {{name.location}}
        </li>
    </ul>
</div>
    <script type="text/javascript">
    function List($scope) {
        $scope.names = [
        {"firstname": "Carl",
        "lastname": "Luyk",
        "age": 20,
        "location":"Berlin"},
        {"firstname": "Carl",
        "lastname": "Moreen",
        "age": 20,
        "location":"Hamburg"},
        {"firstname": "Tom",
        "lastname": "Luyk",
        "age": 25,
        "location":"New York"},
        {"firstname": "Caren",
        "lastname": "Tilt",
        "age": 20,
    "location":"Paris"},
        {"firstname": "Caren",
        "lastname": "Orail",
        "age": 30,
        "location":"Hamburg"},
        ];
    $scope.getData= function(){
    //here I would like to get the data structured like $scope.names..is that possible?
    alert('changed');

    }

    }
    </script>

</body>
</html> 

2 个答案:

答案 0 :(得分:7)

试试这个:

Search: <input ng-change="getData(names, query)" ng-model="query">

在你的控制器内:

$scope.getData = function (names, query) {
  $scope.queryData = $filter('filter')(names, query));
};

所以$ scope.queryData现在是你的结果集合。

答案 1 :(得分:3)

你得到“$ filter is underfined”的原因是你没有将它注入你的控制器。定义控制器时,请执行以下操作:

app.controller('list', function($scope, $filter) {
  $scope.getData = function (names, query) {
    $scope.queryData = $filter('filter')(names, query));
  };
}

您还可以在控制器中定义搜索。

$scope.queryData = $filter('filter')(array, search-expression));

希望有所帮助!