Pass information from the controller to the view in AngularJS

As I am still relatively new to Angular, I believe I might be overlooking a crucial step in transferring data from the controller to the view for display.

The specific functionality I am trying to achieve involves a user entering search criteria into a form and then clicking the submit button. This action triggers a function in the controller (getQuote()) which initiates an API call. The response from this call should then be displayed on the redirected view. While I have been successful in printing the response to the console using my function, the view itself remains empty.

Below is the code snippet:

Jade template for search form

div(ng-controller="StockCtrl")
    form(action="/#/stock/quote")
        div(class="form-group")
            h3 Enter your stock symbol
            input(type="text" placeholder="AAPL ..." class="form-control input-lg" ng-model="formData.symbol")
            br
            h3 What time period are you interested in?
            input(type="date" id="startdate" class="form-control input-lg" ng-model="formData.startdate")
            br
            button(type="submit" class="btn btn-primary btn-lg" ng-click="getQuote()") Compare

Controller

var stockrControllers = angular.module('stockrControllers', []);

stockrControllers.controller('StockCtrl', ['$scope', '$http', '$routeParams',
    function ($scope, $http, $routeParams) {

  $scope.stockData = [];
  $scope.formData = [];

  $scope.getQuote = function(startdate){
    var symbol = $scope.formData.symbol;
    var startdate = new Date($scope.formData.startdate);
    var startday = startdate.getDate();
    var startmonth = startdate.getMonth() + 1;
    var startyear = startdate.getFullYear();
    var enddate = new Date(startdate);
    enddate.setDate(startday + 5);
    var endday = enddate.getDate();
    var endmonth = enddate.getMonth() + 1;
    var endyear = enddate.getFullYear();

    //format dates to work with API call
    startdate = startyear + "-" + startmonth + "-" + startday;
    var enddate = endyear + "-" + endmonth + "-" + endday;

    $http({
      method: 'GET',
      url: 'api/stock/' + symbol + '/' + startdate + '/' + enddate
    }).then(function successCallback(response) {
        $scope.stockData = response;
        console.log($scope.stockData);
      }, function errorCallback(response) {
        console.log('Error:' + response);
    });

  };

}]);

Jade template for view to print data

h1 Stock Data

div(ng-controller="StockCtrl")
    div(ng-repeat="stock in stockData")
        p stock data: {{stock}}

When I avoid wrapping my API calls within a function and use an if statement (like if($scope.formData){..}), the API response can be displayed perfectly fine in the view. However, when the call is placed within a function, it prevents the data from being rendered on the page.

Answer №1

If you combine the two separate div(ng-controller="StockCtrl") into a single div, you will be able to see the $scope.stockData more clearly:

div(ng-controller="StockCtrl")
    form(action="/#/stock/quote")
        div(class="form-group")
            h3 Enter your stock symbol
            input(type="text" placeholder="AAPL ..." class="form-control input-lg" ng-model="formData.symbol")
            br
            h3 What time period are you interested in?
            input(type="date" id="startdate" class="form-control input-lg" ng-model="formData.startdate")
            br
            button(type="submit" class="btn btn-primary btn-lg" ng-click="getQuote()") Compare

    div(ng-repeat="stock in stockData")
        p stock data: {{stock}}

Answer №2

Make sure to update your API call code to properly handle the response data from the server.

$http({
    method: 'GET',
    url: 'api/stocks/' + symbol + '/' + startDate + '/' + endDate
}).then(function onDataSuccess(response) {
    $scope.stockInfo = response.data;
    console.log($scope.stockInfo);
}, function onError(response) {
    console.log('Error encountered: ' + response);
});

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

Is it possible to modify the 3D object within WebGL using Three.js only in certain scenarios, such as adding textures or moving the mouse?

Utilizing a 3D object exported from Blender, specifically cylinder.obj, I have successfully implemented its rendering on the screen with the help of Three.js. The functionality to rotate the object using mouse input has also been integrated. This entire vi ...

Protractor is unable to utilize local properties defined within the .then statement

Lately, I've been working on streamlining my Protractor e2e tests using the Page Object model for better reusability. Each Page Object typically starts with defining elements on that page followed by local functions. Here's an example: 'use ...

Need to ensure that an AJAX form doesn't resubmit without the need for a page

Encountering a peculiar mystery issue here... I have created a button on a webpage that triggers a form submission. The form is enclosed within a DIV, which dynamically updates to display the modified data. (this is embedded in a smarty template) form: ...

Display elements on hover of thumbnails using CSS

I'm struggling with the logic of displaying images when hovering over corresponding thumbnails using only CSS. If necessary, I can do it in JavaScript. Here's my latest attempt. <div id='img-container' class='grd12'> ...

Mastering the art of asynchronous programming with $.getJSON

This is how I am approaching the situation: $.getJSON(url1, function(response1){ if(response1.status == 'success'){ $.getJSON(url2, function(response2){ if(response2.status == 'success') { $.getJSON(url3, functi ...

Encountering a response code of 401 results in the exclusion of certain code

I'm currently developing an application using Ionic v1, Express, MongoDB, and Node.js. In my code for checking user authentication, I have the following snippet: checkAuthentication: function(token) { console.log(token); retur ...

The functionality of useMemo is compromised when changes are made to sessionStorage

I'm facing an issue with my app where the header contains an icon that should only be shown when the user is logged in. I store the login status in sessionStorage, but the component doesn't re-render when it changes. I attempted to use useEffect ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Creating a dynamic dropdown menu in Laravel 5.3 - A step-by-step guide

Here is my HTML code: <div class="form-group has-feedback{{ $errors->has('kdkotama') ? ' has-error' : '' }}"> <select class="form-control" name="kdkotama" id="kdkotama"> <option value="">---- ...

Using ngBindHtml in combination with angularUI in a template may yield a different outcome compared to using $sce.parseAs

Edit: Problem solved! Details at the end of the question. Within my directive sfNgFieldWrapper, I have integrated a tooltip from angularjUI ui-bootstrap. The text for the tooltip is designated by tooltip="{{ttpText}}". The issue arises when the text con ...

How can I call the telerik radgrid.databind() function using a JavaScript function?

Currently, I am coding in ASP .NET and have an ASPX page featuring a Telerik RadGrid. I am curious to know if it is feasible to call the RadGrid.DataBind() method from within a JavaScript function? ...

Unlock the potential of localstorage in dropdown toggle menus with jQuery and HTML

Do you have a moment? I need some help with using local storage in my dropdown toggle menu. Below is the HTML code that I am working with: <li class="nav-item" id="sidebar"> <a class="sidebar-heading" href="#thirdSubmenu" data-toggle="collaps ...

Capturing and saving location data without internet connection, and then displaying markers once connectivity is restored

I am currently developing a web application that will monitor the user's location. I want to ensure its reliability, so even if the user loses internet connection, the application will continue tracking their location (since GPS does not rely on inter ...

Is there a need for an extra loader for pdfjs-dist in a React application?

I am facing an issue with the pdfjs-dist dependency in my React app. I am unsure of what changes I made that caused this problem. My environment includes node v14.16.1, npm v7.9.0, react 17.0.2, react-scripts 4.0.3, and pdfjs-dist 2.7.570. When I run npm s ...

What are some examples of MySQL node insertion queries with a pair of values?

I need help with my current JavaScript code snippet. var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'codify', port: '8889' } ...

How to use ng-if directive in Angular.js for lists

Trying to implement ng-if in angular.js. JSON data: "data":[{ "status":"true", "name":"blabla", "group":true, "group_id":"123gr", "id":"xx1" },{ "status":"true", "name":"blabla2", "group":false, "id":"123gr", "group_id":"null ...

Having trouble with an AngularJS directive that is causing all checkboxes to become unchecked

Hello and thanks for taking a look at my problem. I'm working on a directive that displays a list of parents and their children. Each parent has a checkbox that allows the user to print only the checked parents (e.g., if they check parent #1 and #5, ...

Exposing the secrets of the Ajax module

Here is the code snippet I am working with: my.data = function () { var getAuth = function (userName, password) { var model = JSON.stringify({ "UserName": userName, "Password": password }); var result; $.ajax({ url: m ...

CKEditor5: Unable to access the 'pluginName' property because it is undefined

I am facing a challenge in creating a custom image plugin for CKEditor that can seamlessly integrate with my own image upload system. While trying to set up this plugin, I encountered some difficulties. Oddly enough, the "out-of-the-box" plugins work perfe ...

Transform a span into a div while retaining its content and styles, ensuring compatibility with Internet Explorer

Is there a reliable JavaScript method to convert a span into a div while preserving its contents and the original classes of the span? The classes are pre-set, so hardcoding should be possible. <span class="my class"> <p class="conten ...