How can data be effectively passed between templates in Angular?

I have two templates: in the first template, I am using a function and after its successful execution, I want to retrieve data in the second template. How can I achieve this? Both templates are utilizing the same controller.

First Template:

<form ng-submot='vm.search(q)' class="header-search">
            <input class="header-search-input" ng-model='q'  placeholder="Search">
            <button type="button" class="btn btn-default ic-search" aria-label="Left Align" ng-click='vm.search(q)'>
              <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
            </button>
        </form>

Second Template:

<h3>Search Results for: {{q}}</h3>
<ul ng-repeat='item in items'>
    <li>{{item.name}}</li>
</ul>

Controller:

(function() {
    'use strict';

    angular
        .module('beo.layout.controllers')
        .controller('NavbarController', NavbarController);

    NavbarController.$inject = ['$scope', '$http', '$location'];
    function NavbarController($scope, $http, $location) {

        var vm = this;

        vm.logout = logout;
        vm.search = search;

    function search(q) {
        $http.post('/api/v1/search/', {
            q: q
        }).success(function(data) {
            $location.path('/search/')
            $scope.q = q;
            $scope.items = data;
        })
    }

})();

Answer №1

For optimal performance, I recommend utilizing caching. When working with multiple templates, loading a new template may also result in reloading the controller. To avoid this, consider saving search results from the first template in the cache. Then, upon redirecting to another template, simply check the cache for any existing results and display them if available.

Answer №2

By assigning the value of the input field to $scope, you can effectively transfer data from the initial template to the subsequent one.

Answer №3

Implement the ng-if directive to toggle between two sets of HTML snippets. Also, keep in mind that in Angular, the term template holds a special meaning, similar to template in a directive.

For instance:

<div ng-if="!items">
  <form ng-submot='vm.search(q)' class="header-search">
    <input class="header-search-input" ng-model='q'  placeholder="Search">
    <button type="button" class="btn btn-default ic-search" aria-label="Left Align" ng-click='vm.search(q)'>
    <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
    </button>
  </form>
</div>

<div ng-if="items">
  <h3>Search results for: {{q}}</h3>
  <ul ng-repeat='item in items'>
    <li>{{item.name}}</li>
  </ul>
</div>

Once data is successfully fetched and the variable items becomes true, Angular will automatically switch to the second template.

NOTE: It's not recommended to use both vm (this) and $scope within the same controller simultaneously.

Answer №4

If you want to follow the Angular approach, utilizing directives is key. With directives, it's possible to access controllers from other directives in order to exchange data as required. You can refer to this example for more insight: How to utilize controller requirement in an angularjs directive

Answer №5

To retrieve data after a user clicks on the search button, you will need to use the vm.search function in your code which is located within the controller. This function should make an api call to fetch the data as shown in the example below.

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController);
  
  function DefaultController() {
    var vm = this;
    vm.items = [];
    
    vm.search = search;
    
    function search(searchTerm) {
      // perform ajax call and set data here on vm.items property
      vm.items = data;
    }
  }
  
  var data = [
  { name: 'Audi' },
  { name: 'Lamborghini' },
  { name: 'Jaguar' }
  ];
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
    <form name="searchForm" novalidate="novalidate" ng-submit="searchForm.$valid && ctrl.search(ctrl.searchTerm)">
      <label for="searchBox">Search</label>
      <input type="text" name="searchBox" ng-model="ctrl.searchTerm" ng-required="true">
      <button ng-click="isSubmitted = true">Submit</button>
      <span style="color: red;" ng-show="isSubmitted && searchForm.searchBox.$invalid">Search term is required</span>
    </form>
    
    <label ng-show="ctrl.items.length">Items matching your search</label>
    <div ng-repeat="item in ctrl.items">
      {{item.name}}
    </div>
  </div>
</div>

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

Exploring the functionalities of AngularJS' ng-options when working with select elements

In my search through other posts, I came across this issue but couldn't find a solution. Here is the array in question: $scope.items = [ {ID: '000001', Title: 'Chicago'}, {ID: '000002', Title: 'New York' ...

disable any other active toggle in a vue component

Exploring JavaScript and how to accomplish the following tasks Snapshot The issue I am facing is that if I click on a product, and then click on settings, both are open. However, I want only the currently clicked toggle to be open. For instance, if I cl ...

Extracting the call from REST API in JSON format

Working with a third-party database using a REST API, I encountered an error response (as expected). Here is the code snippet: transaction.commit(function(err) { if (err){ var par = JSON.parse(err); \\ leading to error: SyntaxError: Unexpecte ...

Why am I unable to access the array once the loop has finished?

While utilizing the Google Maps API and AngularJS (1.5.8), I encountered an issue where I couldn't access markers that were created in a loop. The code snippet below is located inside the initMap function: var markers = []; for(var i=0; i<10; i++ ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

Switching visual representation that appears upon clicking the dropdown menu

Issue with Duplicating Dropdown and Image Change const image = document.querySelector('.item__img'); const checkbox = document.querySelectorAll('.imgOption'); function handleChange() { let imgsrc = this.getAttribute("data-value ...

JavaScript sticky navigation bar - error displayed in console

Hey there, I'm having an issue with my Sticky-menu. I've been trying to troubleshoot it but keep getting these console error messages: 1. Cannot read property 'offsetTop' of null at HTMLDocument. 2. Cannot read property 'class ...

Unable to update data from false to true in vue.js

What I'm trying to do is change the data from false to true in order to conditionally render a button when a payment has succeeded. When making an axios call, I receive 'succeeded' as the response in the JSON object and can log it to the con ...

Make sure the auto import feature in TypeScript Visual Studio Code Editor is set to always use the ".js" extension

At times, the auto-import completion feature includes the .js extension, but inconsistently. When this extension is missing in the TypeScript source, the emitted JavaScript file may encounter runtime issues like module not found error since the tsc compile ...

Exploring an alternative perspective on successful login in angular.js

Today was the beginning of my project to convert a website to angular.js. The main page is served by index.html and includes ng-view for other views such as login and signup. Working closely with a backend developer, I have successfully integrated a rest c ...

Fixing Firefox Bug: How to Eliminate Non-Numeric Characters from "Number" Input Fields

Completing this task seems straightforward. I need to eliminate any non-numeric characters from an input field specified as type "number" in Firefox when a key is pressed. The code snippet provided: $("#field").on("keyup", function() { regex = /[\& ...

Custom virtual properties can be set in Mongoose by utilizing the return value in a callback function

I've been searching all over for a solution to my issue, but I can't seem to find the right answer. I'm currently using MongooseJS as my ODM and I'm attempting to create virtual getters that can retrieve, process, and display informatio ...

The NPM START ERROR message is indicating a problem with locating a file in npm

Having an issue with npm while trying to set up a basic server using node.js. Hello network! I've searched through forums, videos, and articles for solutions, but none have resolved my problem. The error message indicates that the package.json file ...

Combining multiple HTML elements onto a single page with just one function

I am trying to dynamically import specific HTML content into a new page, rather than the entire page itself. The issue I am encountering is that I have to create a document load function for each individual item I want to import. Is there a more efficient ...

Expand or collapse Angular Material Accordion depending on selected Radio button choice

Is it possible to use a mat-accordion with radio buttons where each panel expands only when its corresponding radio button is selected? I have the radio buttons functioning correctly, but the panels are expanding and collapsing with every click rather than ...

dynamically loading jQuery scripts and content via ajax

I have a webpage that displays a file tree with links to different pages and subfolders. The folders are getting too large, so I want to use a jQuery script to hide them. However, the issue is that the tree is loaded dynamically through ajax, so the jQuery ...

Preserve the chosen option in a dropdown menu even after a postback using JavaScript

Seeking Help in Retaining Dropdownlist Selected Value After Postback In my efforts to retain a dropdownlist selected value after postback, I have been exploring various methods. I extract the selected values from the dropdownlist and store them in local ...

What is the best way to transfer weather data from a server to an HTML text area box?

Recently, I delved into the world of expressJS to set up a local server (localhost:3000). With the power of JavaScript (specifically in a file named app.js), I was able to send simple messages like "Hello World" to the browser. However, now I find myself f ...

Eliminate any null strings from an object by comparing the object's previous state with its updated state

I am currently implementing an exemptions scheduler using react-multi-date-picker. The react-multi-date-picker component is integrated within a react-table in the following manner: const [data, setData] = useState(0); const [dateValues, setDateValues] = us ...

Can you explain the function of the "staticMoving" property in TrackballControls?

I was exploring the library module known as THREE.TrackballControls when I came across an interesting property within an instance of the module called staticMoving. This property appears to be connected to another property called dynamicDampingFactor. Howe ...