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.