Search code examples
htmlangularjscookiesfilterangularjs-ng-repeat

AngularJS, how to get and set a filter defined in ng-repeat from within controller?


The simple HTML block below loops through a list of person objects in JSON format to display their first and last names. The two input boxes above the ng-repeat are linked to the filters based on firstName and lastName accordingly. So far all is good, working.

My goal is to capture the user input in filter fields in the controller when they leave the page, and then repopulate the filters when they return to the page. I am able to capture/get the search field values by using $scope.$on("$destroy"... when the page is left. However, when I try to set those fields, $scope.search.firstName = 'John' I am getting an error: $scope.search is undefined. My goal is to use cookies to keep and then reset the filter field values, but I am not sure why the set does not work and how to fix it.

<table>
    <tr>
        <td><input type="text" ng-model="search.firstName" /></td>
        <td><input type="text" ng-model="search.lastName" /></td>

    </tr>
    <tr ng-repeat="person in personList | filter:search:strict">
        <td>
            <span class="col-xs-offset-2">
                {{person.firstName}}
            </span>
        </td>


        <td>
            <span class="col-xs-offset-2">
                {{person.lastName}}
            </span>
        </td>

    </tr>
</table>

// fragments from controller

$scope.search.firstName = 'John'; // this does not work, returns error

$scope.$on("$destroy", function () {
    console.log($scope.search.firstName); // this works
    console.log($scope.search.lastName)); // this works
});

Solution

  • If you are getting this TypeError: $scope.search is undefined, you should try to set those values by first defining search as an object.

    $scope.search = { 'firstName': '', 'lastName': ''};
    $scope.search.firstName = 'John';