AngularJS - $filter inside controller

by sqiudward

HTML

<div ng-app>
    <div ng-controller="MyCtrl">
        <input type="text" ng-model="search">
        <table>
            <tbody>
                <tr ng-repeat="item in items">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.isSelected}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

JavaScript

function MyCtrl($scope, $filter)
{
    $scope.items = [
        {id:1, name:'John', isSelected: true},
        {id:2, name:'Steve', isSelected: false},
        {id:3, name:'Joey', isSelected: true},
        {id:4, name:'Mary', isSelected: true},
        {id:5, name:'Marylin', isSelected: false}];
    
    $scope.items2 = $scope.items;
    
    $scope.$watch('search', function(val)
    { 
        $scope.items = $filter('orderBy')($scope.items2, 'isSelected', true);
    });
}