Cassus
Cassus

Reputation: 199

AngularJS Filter expression not being updated

I have am dealing with two HTML files and one controller. In one HTML file I have a search bar:

  <a ui-sref="allSubmissions">
    <input id="searchBar" ng-controller="submissions" ng-model="searchString" class="searchBar" type="text" placeholder="Search">
</a>

Along with some other stuff. In a separte HTML file, I have a list of submissions that I populate with ng-repeat:

<div class="container" ng-controller="submissions">
    <ul class="subsList">
        <ul>
            <li ng-repeat="item in submissionCollectionTest | filter: searchString" class="submissionDivider hover">
                <span class="ageText">{{item.age}}</span>
                <span class="submissionsText">{{item.submission}}</span>
                <span class="descriptionText">{{item.description}}</span>
            </li>
        </ul>
    </ul>
</div>

Along with some other code. It makes sense in my complete app that these files be separate, however, I cannot get the search input to tie to the filter expression and automatically update. In my controller, i have the following scope variable:

myApp.controller('submissions',function($scope){


$scope.searchString = '';

When I click in the search bar, it takes me to the new page with shows all the content populated from the ng-repeat, then I want to filter the content by typing in the search bar. This does work when I have the search bar code in the same place as the content. How can I update "searchString" globally so that the filter responds when it changes? Thanks

Upvotes: 1

Views: 96

Answers (1)

Rob
Rob

Reputation: 1860

You could use a broadcast from one controller and listen in another. If you're using multiple routes, then you'll want to store the search term in a service.

Example: https://jsfiddle.net/h0bd88dc/

function SearchSubmissionsCtrl($rootScope,Service) {
     var vm = this;
     vm.searchString = Service.searchString;
     vm.search = search;

     function search() {
        Service.searchString = vm.searchString;
        $rootScope.$broadcast('search', vm.searchString);
     }
  }

  function SubmissionsCtrl($scope,Service) {
     var vm = this;
     vm.searchString = Service.searchString;
     vm.items = [{
        age: 22,
        submission: 'Yes',
        description: 'Yo'
     }, {
        age: 5,
        submission: 'Derp',
        description: 'Hey'
     }];

     $scope.$on('search', function(e, string) {
        vm.searchString = string;
     })
  }

  function Service() {
    var service = {
        searchString: null
     };

     return service;
  }

Upvotes: 2

Related Questions