Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global search box in angular

I want to implement a search box that changes what it searches based on whichever controller is being used. If you are on the "posts" view it will search the posts api, if you are on the videos view, it searches the videos api. It seems the search box would need its own controller maybe. I'm pretty sure I need to inject a search service into all the model controllers but I'm not exactly sure how to change the url it searches or tie the input to the different controller scopes.

So any ideas how to have a global search box that changes where it searches based on whichever controller is making use of it and tying its state back into a changing view?

like image 606
chris Avatar asked Sep 23 '13 15:09

chris


1 Answers

Client side filtering.

If you are not looking for anything to crazy that can be achieved in a super simple way for global search. I didnt even know if this would work so i just did a quick test and it does. Obviously this could be solved in a much more detailed and controlled way using services and injecting them where they are needed. But since i don't know excatly what you are looking for i will provide this solution, if you like it, great accept it. If you don't i could probably help you with service injection solution

Quick solution is to have an app wide contoller with $rootScope ng-model. Lets call it global.search.

    $rootScope.global = {
        search: ''
    };

For the app wide search input.

<form>
    <label>Search</label>
    <input ng-model="global.search" type="text" class="form-control" />
</form>

In separate partials you just need to filter data based on the global.search ng-model. Two examples

<p ng-repeat="post in posts | filter: global.search">{{ post.name }}</p>

Second template with different scope

<p ng-repeat="video in videos | filter: global.search">{{ video.name }}</p>

Note how they both implement | filter: global.search. Whenever global.search changes, any filters in the current view will be changed. So posts will be filtered on the posts view, and videos on the videos view. While still using the same global.search ng-model.

I tested this, it does work. If you need more detail explaining the setup and child controller hierarchy let me know. Here is a quick look at a full template

<html>

<body ng-controller="AppController">
    <form>
        <label>Search</label>
        <input ng-model="global.search" type="text" class="form-control" />
    </form>

    <div ui-view="posts">
        <div ng-controller="PostController">
            <p ng-repeat="post in posts | filter: global.search">{{ post.name }}</p>
        </div>

    </div>

    <div ui-view="videos">
        <div ng-controller="VideoController">
            <p ng-repeat="video in videos | filter: global.search">{{ video.name }}</p>
        </div>

    </div>

</body>

</html>
like image 180
j_walker_dev Avatar answered Nov 15 '22 08:11

j_walker_dev