i have a json file from the backend and I want to display it via ng-repeat
. I do not know how to get the element.
In the html file, I want to do something like this
<div ng-repeat = "answer in answers">
{{answer}}
</div>
on my app.js file, I know I am getting the right data as I have displayed it on the console.log
socket.on('got message', function(data){
console.log(data);
});
but I do not know how to convert the data to answer. the data on the console.log showed the following, if I expand it, how I get them into {{answer}}
Global Quote:
01. symbol: "MSFT"
02. open: "186.9500"
03. high: "187.2500"
04. low: "185.8520"
05. price: "186.6900"
06. volume: "5185159"
07. latest trading day: "2020-02-20"
08. previous close: "187.2800"
09. change: "-0.5900"
10. change percent: "-0.3150%"
I do not have to use socket, it is a local JSON file, only if I know how to read it into {{answer}}
.
{ "Global Quote":{
"01. symbol":"MSFT",
"02. open":"186.9500",
"03. high":"187.2500",
"04. low":"185.8520",
"05. price":"186.2950",
"06. volume":"5758297",
"07. latest trading day":"2020-02-20",
"08. previous close":"187.2800",
"09. change":"-0.9850",
"10. change percent":"-0.5260%"
}
}
But I am not sure how to pass the data from app.js
to the html file. In my app.js
file, I have
socket.on('got message', function(data){
$scope.answers = new Array;
$scope.answers = data;
console.log($scope.answers);
});
but $scope.answers
is passing to the html file
One approach is:
<div ng-repeat="(key, value) in answers['Global Quote']">
{{key}} : {{value}}
</div>
For more information, see
AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.
You can also use $apply() to enter the AngularJS execution context from JavaScript:
socket.on('got message', function(data){
$scope.$apply(function() {
$scope.answers = data;
console.log($scope.answers);
});
});
Keep in mind that in most places (controllers, services) $apply has already been called for you by the directive which is handling the event. An explicit call to $apply
is needed only when implementing custom event callbacks, or when working with third-party library callbacks.
For more information, see