Learn how to switch between search and results views in Angular while also transferring data

Currently, I'm attempting to tackle a common task that I've yet to encounter an example of.

Display 1 and Control 1 :

In this view, there is a basic textbox with ng-model="searchTerm" and ngSubmit event. After the user enters their search term, a webservice call is made to retrieve results for display on the next screen.

Display 2 and Control 2

Upon hitting submit, the view transitions to a results screen where the data fetched from the webservice is shown.

1) What would be the typical method for visually changing screens in this scenario - employing routing and view manipulation? Or is it better to use ng-show/ng-hide?

2) How can I effectively pass the search term from control 1 to control 2?

Answer №1

If implemented, the code structure would resemble the following (not tested):

View 1 and Controller 1:

View:

<form ng-submit="showResults(searchTerm)">
    <input type="text" ng-model="searchTerm">
</form>

Controller:

$scope.showResults = function (searchTerm) {
     // Redirect to another page for query handling
     // Make sure to include $location in your controller
     $location.url('/results?q=' + encodeURIComponent(searchTerm));
});

View 2 and Controller 2:

Assuming this view is linked to /results route.

Controller:

app.controller('SearchResultsCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
    // Watch the query string parameter for changes to update and rerun the query
    $scope.$watch(function () {
        return ($location.search() || {}).q;
    }, function (searchTerm) {
        // Call web service using $http or other methods, e.g.
        $http.get('/api/search?q=' + searchTerm).then(function (data) {
            $scope.results = data;
        });
    });
 }]);

Then manipulate the results scope property as needed within your view.

Answer №2

When it comes to routing, your page will undergo changes and there will be interactions between the client and server. This interaction may lead to increased overhead if bandwidth is limited. On the other hand, using ng-show and ng-hide will simply toggle the display of an existing page, essentially creating a single-page application. The choice between the two depends on the specific requirements of your project.

Consider what functionality you want your application to have. If storing search strings is crucial for your application, utilizing a service might be the way to go. However, keep in mind that this approach won't retain values across different sessions.

As mentioned by GregL in the comments, appending search strings to the URL might not be ideal for handling multiple search hits or navigating previous searches. In such scenarios, using a service would be more efficient. But if storage and retaining previous values are not necessary, sticking with routeParams could suffice.

Answer №3

One effective method of working with search functionality is by incorporating the search query into the URL as a corresponding GET parameter. This approach is commonly seen in traditional websites as well as in single page applications. The key advantage is that the search results screen should accurately reflect the current search term and be easily bookmarked.

To implement this, you can utilize the ngRoute module to create a simple routing system.

Here's a basic example:

// Define routes
app.config(function($routeProvider) {
    $routeProvider.when('/home', {
        controller: 'HomeController',
        templateUrl: 'home.html'
    })
    .when('/search-results', {
        controller: 'SearchResultsController',
        templateUrl: 'results.html'
    })
    .otherwise('/home');
});

// HomeController manages form submission and navigates to SearchResultsController
app.controller('HomeController', function($scope, $location) {
    $scope.search = function() {
        $location.path('/search-results').search({query: $scope.query});
    };
});

// SearchResultsController retrieves search query from URL and executes search request
app.controller('SearchResultsController', function($scope, $routeParams, $location) {
    $scope.query = $routeParams.query;
    $scope.url   = $location.absUrl();

    // perform search operation using $scope.query
});

Try out a Simple Demo here: http://plnkr.co/edit/FMRTTbxdNv0pGSYpfwve?p=preview

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

Physically eliminate (and obliterate) a component from keep-alive

Is there a way to access and programmatically unmount a component instance loaded from Vue Route and persisted using <keep-alive> and <component>? I am working on a dynamic tab system where each tab renders a URL which displays its declared com ...

XPath using JScript

I'm a beginner with Selenium and I'm curious about how the value in the text box is loaded when there's no value visible in the HTML tag: <input type="text" name="qty" id="qty" maxlength="5" value="" title="Qty" class="quantity-input qty ...

Differences Between JavaScript and TypeScript Classes

I'm a novice when it comes to TypeScript and JavaScript classes! While learning TypeScript, I created a simple code snippet like this: class User { name: string; email: string; constructor(name: string, email: string) { this.name = name; ...

Steer clear of performing DOM manipulation with jQuery within an ng-repeat directive

As a beginner in Angular, I am currently developing a simple CRUD application. I have learned that it is recommended to avoid using jQuery for DOM manipulation whenever possible. Currently, I am faced with the challenge of removing a row from the DOM when ...

Tips for dynamically updating the div class based on the model's value

How can I dynamically change the CSS class of a bootstrap element based on a value? I would like to display a div in green if the value is "OK" and red otherwise. If status = "OK", it should look like this: <div class="small-box bg-green">, else < ...

Problem encountered while using AJAX to load a PHP script, triggered by an onclick event;

My expertise lies in HTML, CSS, JavaScript, and PHP. However, I find myself lacking in knowledge when it comes to jQuery and Ajax. While I work on web design projects involving bars and nightclubs that prioritize style over performance, my current job dema ...

What causes Angular to automatically add 'localhost' to the URL when using $location.path?

When I try to use the code below to redirect me to a specific page (redirectUrl), it instead adds 'localhost' in front of the redirectUrl resulting in "localhost/http://localhost/example/page". Is there a way to prevent this from happening? var ...

Discover the correct steps to transition from using particles.js to the react-tsparticles package

Migrating from react-particles-js to react-tsparticles-js Hi there! I'm currently facing an issue with my ReactJS website here, which is deployed using Netlify. The error code below keeps popping up, and I believe it's related to the transition ...

Guide to invoking a method in the child window using AngularJS

My Angular JS app comes with a "view" button. When this button is clicked, it triggers a method that updates the content on the same page. However, I've received a new requirement where clicking the view button should open the content in a new tab. H ...

Creating an attractive image carousel using jQuery or YUI for your website

I am searching for a javascript-based slideshow solution for images. I have received the following requirements: The slideshow should fade one image into another, looping back to the first image after all images have been displayed It must include naviga ...

Discover the way to retrieve PHP SESSION variable within JavaScript

I'm currently working on developing a platform for image uploads. As part of this project, I assign a unique identifier to each user upon login using $_SESSION['id'] in PHP. Now, I am looking for a way to verify if the $_SESSION['id&apo ...

Is it feasible to implement multiple selection columns in ng-grid, such as columns with checkboxes and radio buttons?

I'm in the process of building a table utilizing ng-grid (still learning about angularjs and ng-grid). The table should have the following columns: A column for checkbox selection. A column for radio button selection. Additional columns for data. H ...

What is the sequence in which Jest executes its tests?

A fascinating challenge I've taken on involves testing a card game created in JavaScript using Jest. Currently, I have developed two tests: one to verify the creation of a 52-card deck and another to confirm that the player is dealt two cards at the ...

Awaiting fulfillment - Promise remains pending as loop executes queries

I have a scenario where I receive an array containing multiple data elements and need to perform a query for each element in the array. However, this is resulting in a promise pending response. How can I resolve this issue? What could be causing it? getFa ...

Show ng-message when email is invalid in Angular Material without using ng-pattern

I need to show an error message that says Please enter valid email. when an invalid email is entered, but I cannot use the ng-pattern attribute with this specific regex pattern. <md-input-container class="md-block" flex-gt-xs> <label>Ema ...

Trigger a notification from one webpage to another (PHP, JavaScript, HTML)

I'm currently working on a website that consists of both a receptionist page and a user page with multiple logins. The receptionist page displays a table listing all logged-in users, including their status (either ready or busy). This table is refresh ...

Interconnected realms communication

I'm currently in the process of developing a Facebook iframe app. At one point, I initiate a friends dialog from Facebook and embed an HTML button to add some customized functionality for my app. dialog = FB.ui({ method:'fbml.di ...

Using GSAP to create a staggered animation with a negative delay

Seeking a Solution: I am curious if there is a method to incorporate a negative delay into the staggerFrom / staggerTo functions within greensock? Issue at Hand: The current animation I have in place is extending longer than desired. It would be benefic ...

Is it Better to Perform Manual Change Detection in AngularJS or Angular 2?

My issue involves working with a sizable data list where each element has a filter applied. In order to optimize performance due to potentially adding numerous attributes to each entry, I seek to update the list only when there is a change in the data (eve ...

Integrating data binding within a .append function using AngularJS

I followed this code example (http://jsfiddle.net/ftfish/KyEr3/) to develop a form. However, I encountered an issue with an input having ng-model set to "value" and needing to display that value within {{ }} in a TD: angular.element(document.getElementByI ...