Search code examples
angularjssearchviewinstant

Instant search between different views AngularJs


I'm using ui-router in one AngularJs Project

I have two views like this:

.state('index', {
            url: '/',
            views: {
              '@' : {
                templateUrl: 'layout.html'
              },
              'top@index' : { templateUrl: 'partials/layout/top.html'},
              'main@index' : { templateUrl: 'partials/layout/main.html'}
            }
        })

Top and main.

Top view is a nav input search, Main view is where the results have to be displayed, filtering ng-repeat or whatever.

I need to search in the search box and the results must be displayed in the main view at the same time i'm typing in top view.

This only happens when I put the search box in the index.html, but it doesn't work when i put the search box in the top view.


Solution

  • Use the combination of the $rootScope.$broadcast and $scope.$on. Basically you may put the $scope.$on in differents views and all the scopes subscribed to event executed by $rootScope in the TopController may listen the event.

    In the top controller:

    angular
         .module('exampleApp')
         .controller('TopController', TopController);
    
        TopController.$inject = ['$rootScope'];
    
        function TopController($rootScope){
            var vm = this;
    
            vm.search = function(textSearch) {
                $rootScope.$broadcast('top:search', textSearch);
            }
    
        }
    

    In the main controller:

    $scope.$on('top:search', function(event, searchInput){
                console.log(searchInput);
            }); 
    

    Check this: http://codepen.io/gpincheiraa/pen/eJzQpE