Sort and display only certain table rows based on the searchbox input

My application is made up of the following components:

The index view containing the navbar and search box, managed by a nav controller. Two HTML pages within an ng-view element, each with its own controller - customerController and contactsController. These pages display tables populated with data retrieved from a service.

How can I pass a value from the navbar controller to the other two controllers in order to filter the table? The ng-view is not nested inside the navController scope.

This is my routing configuration:


app.config(function ($routeProvider) {
$routeProvider
    .when("/Customers", {
        templateUrl: "app/customers-list.html",
        controller: "customerController"
    })
    .when("/Contacts", {
        templateUrl: "app/contacts-list.html",
        controller: "contactController"
    })
    .when("/Prospects", {
        templateUrl: "app/saleprospect-list.html",
        controller: "prospectController"
    })
    .when("/Prospects/add", {
        templateUrl: "app/salesprospect-add.html",
        controller: "addController"
    })
    .when("/Prospects/:index", {
        templateUrl: "app/salesprospect-add.html",
        controller: "editController"
    })
    .otherwise({
        redirectTo: "/Customers"
    })
});

Answer №1

Utilizing angularjs custom events is a great way to transfer information between different parts of your application.

For more details, check out these resources:

How do I create a custom event in an AngularJs service

Working with $scope.$emit and $scope.$on

Data can be sent along with these events, allowing functions that are listening for them to access and utilize the data as needed.

Answer №2

If you're looking for ways to facilitate communication between controllers, there are various solutions available. One approach is utilizing events as suggested by @ArslanW, while other methods may involve the use of services.

As a recommended practice, storing the search text in the URL as query parameters can be beneficial. This way, even if a user decides to refresh the page, the search results will remain intact because the search text can be retrieved from the URL's query parameters.

An excellent example of this functionality can be seen on Github.com's issue tracker. Users can search for issues and even after refreshing the page, the search results persist without any information loss.

To implement this feature, you will need two watchers. One watcher should be placed in your NavController to monitor changes in the search text and update the URL accordingly.

<input type="text" data-ng-model="searchText">

In your NavController, add the following watcher for the input model:

$scope.$watch('searchText', function () {
    $location.search('searchText', $scope.searchText);
});

With the URL now updated, you can utilize it to determine which search text to utilize within your application.

In the controllers for your HTML views (CustomerController and ContactsController) that display tables, watch for changes in the search text:

$scope.$watch(function () {
    return $location.search().searchText;
}, function (value) {
    if (value) {
        //Proceed based on the entered search text.
}
});

This approach allows you to achieve multiple objectives efficiently. The search text remains stored in the URL to prevent data loss upon page refresh, and also ensures effective communication with each controller regarding the entered search text.

Remember to set the reloadOnSearch property to false in your route configuration to avoid page refresh when adding query parameters:

$routeProvider
    .when("/Customers", {
        templateUrl: "app/customers-list.html",
        controller: "customerController",
        reloadOnSearch: false
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to activate a CSS animation?

I've hit a roadblock while attempting to trigger a CSS animation. Here's my CSS: h3[id="balance-desktop"]{ color: black; -webkit-animation-name: gogreen; -webkit-animation-duration: 2s; animation-name: gogreen; animation-du ...

choose a row from the list

Looking for assistance from seasoned professionals as I have been grappling with this issue for a while now. Here's the breakdown of the problem: The list of products that have already been viewed is provided below serial | name | description ...

Tips for assigning a ceiling value specifically to the minValue

Currently, I have a rangeSlider set up with a specific HTML configuration: Click here to view the rangeSlider preview <rzslider data-rz-slider-model="rangeSlider.minValue" data-rz-slider-high="rangeSlider.maxValue" data-rz-slider ...

How to dynamically add a class to an element in ng-repeat that has been newly updated or added in

Hey there, I'm attempting to dynamically apply a class to an element that gets updated on the view. Check out this fiddle for reference! <div ng-app> <div ng-controller="TodoCtrl"> <ul> <li ng-repeat="todo in todos" ...

Unable to assign value to this.name within a $scope function in AngularJS

After developing an AngularJS application using Skinny AngularJS Controllers, everything seems to be functioning correctly. However, I have encountered a problem with the $scope.submit method. I am trying to assign a value to this.name, and then retrieve i ...

Shrink image sizes using PHP

Currently I am trying to find a way to decrease the sizes of images using PHP when the page loads. Despite obtaining the dimensions, I am uncertain about how to proceed with reducing their sizes in PHP. Below is my existing code: <?php $stmt = $db-> ...

Having difficulty aligning the container div in the center

I'm trying to create a centered grid of full-width buttons, but for some reason, I just can't seem to get the container centered. Any suggestions? Check out the code here - https://jsfiddle.net/a6qo6tzL/ Thank you! <div class="Wrapper"> ...

Styling text in table cells using only CSS, without the use of scripting, based on the values within those cells

I have scoured the forum and came across several older threads that suggest it is not achievable with just CSS (the system I am utilizing does not support scripts). Is there a possibility that this has changed or if someone else has an alternative idea? W ...

What is the process for loading this image?

While browsing through this stunning website, I came across a feature that caught my eye. Can someone please explain how the designer displayed the "The magic is loading" effect: The image vanishes once the site has finished loading completely. ...

Implementing div elements in a carousel of images

I've been working on an image slider that halts scrolling when the mouse hovers over it. However, I'd like to use div tags instead of image tags to create custom shapes within the slider using CSS. Does anyone have any advice on how to achieve th ...

The function getComputedStyle(elem).getPropertyValue('fontSize') returns incorrect values when the font size of the element is specified in em units

My current issue involves trying to obtain the font size of an element in the following manner: getComputedStyle(MyTargetElement , "").getPropertyValue('font-size') The result is coming back as 16px, when it should actually be 14px. W ...

The instantiation of the cloudinary module failed because of an error with the injector

I am currently developing a MEAN application based on the template provided by Linnovate. You can find the template at https://github.com/linnovate/mean My goal is to integrate a module called Cloudinary into my application. To achieve this, I followed th ...

I would like to style the input checkbox using CSS

Is there a way to style input checkboxes with CSS that will work on all browsers (Chrome, Firefox, IE 6, 7, and 8)? If jQuery is the only solution, please let me know. It needs to be compatible with all browsers. Can anyone provide guidance on how to ach ...

Enhance the textarea using Javascript when clicked

I am experimenting with styling my textarea using a combination of JAVASCRIPT and CSS. The goal is to make it expand in size from 20px height to 120px height when clicked, using document.getElementById("tweet_area"). However, I am facing an issue where t ...

Integration of Foundation-Apps Angular website with unit testing using Karma-Jasmine

While attempting to run a karma jasmine unit test, I encountered an issue with using angular-mocks and foundation-apps. It's possible that I overlooked something in my setup. I've provided an example project on github for further evaluation due t ...

Directing a webpage to a particular moment within that page

Is it possible to automatically redirect users to a new page at a specific time? I would like visitors to be redirected to a new site starting from 12:00AM on December 31st, without allowing them to access the current site after that time. Is there a way ...

Using a Python class instance as a parameter in a Bottle template

Here is how my class is structured: class Person: def __init__(name=None, id_=None): self.name = name self.id_ = id_ # The current way I am handling it is as follows. The member object is of type Person. return template('index.html&apo ...

`.svg file appearing slightly fuzzy when magnified in Chrome``

After careful consideration, I've chosen to use an SVG for my website logo. However, I am facing an issue with it rendering properly in Google Chrome. When the zoom level is set at 100%, the image appears blurry, but if I zoom out a couple of times, i ...

On a smaller screen size, the event listeners I add dynamically are successfully attached using the exact same HTML, however, they fail to attach on a larger screen size

I recently created a small website where I dynamically add code to HTML divs. Once the data is set, I attach click and mouse enter/leave events using the div's ID. The site consists of plain HTML, javascript, and CSS. However, I noticed that when I v ...

How to Showcase Images in an Ionic 2 App Using HTML Content

This amazing app was built with Ionic 2 technology. It leverages a REST API to retrieve data in JSON format. Interestingly, one of the fields sent from the server is HTML content. <div [innerHTML]="'<p>' + eventMoreDetails.DescriptionHt ...