简体   繁体   中英

Angular search filter not working (data returned by PHP)

I dont get the search filter working.

projects template:

<h3>Projekte</h3>
Search: <input ng-model="searchText">
<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Long Title</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="(key, project) in projects | filter:searchText">
            <td>{{key}}</td>
            <td>{{project.title}}</td>
            <td>{{project.longTitle}}</td>
            <td><button class="btn btn-default" ng-click="edit()"><i class="fa fa-pencil"></i></button></td>
        </tr>
    </tbody>
</table>

controller:

var secProjects = function ($http,$scope, $modal) {

    $http.post('php/data.php').
    success(function(data) {
        $scope.projects = data;
    })

}

php:

while($row = mysql_fetch_object($result)){
        $data[$row->ID] = array ('id'=>$row->ID,'title'=>$row->Title,'longTitle'=>$row->TitleLong, 'textDE'=>$row->DescriptionDE,'start'=>$row->DateStart,'end'=>$row->DateEnd);
    }
    echo json_encode($data);

i hope you can help me :( I think the reason ist the way i get the data in my scope. but iam not sure.

EDIT: Change the PHP solved the Problem:

   $data = array();
   while($row = mysql_fetch_object($result)){
      array_push($data,['id'=>$row->ID,'title'=>$row->Title,'longTitle'=>$row->TitleLong]);
   }
   echo json_encode($data);

The problem is that your backend returns the data as an object instead of an array.
But the filter works only on arrays (according to the docs ):

Selects a subset of items from array and returns it as a new array.


So, you have two options:

1.
Before assigning the data to your scope, convert them from object to array. Eg:

$http.post(...).success(function (data) {
    $scope.projects = [];
    for (var key in data) {
        $scope.projects.push(data[key]);
    }
});

2.
Have your backend return the data as a JSONified array, instead of an object.
The reason PHP is interpreting your $data "array" as an object is that the indices are not sequential (starting from 0). Ie instead of having indices 0, 1, 2... , you had 1,2,3... . (See, this answer for more info.)
To fix this, you can change your code, like this:

$data[] = array (...

See, also, this short demo .

I've duplicated your work, without the service call here . It's exactly the same except for your post (should be a get). And it works fine. Take some more time to check your work. Javascript errors may disable further functionality. .

    $scope.projects = [{
    title: 'one',
    longTitle: 'one long title'
}, {
    title: 'two',
    longTitle: 'two long title'
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM