Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  154] [ 4]  / answers: 1 / hits: 6861  / 10 Years ago, sat, july 26, 2014, 12:00:00

I want to get length my json date. I have service whose take date json from http url. Code looks like this:



---restaurantData.js.coffee---
angular.module('Rest').factory('restaurantData', ['$http', ($http) ->

restaurantData =
data:
restaurants: [{title: 'Loading', discription: ''}]
isLoaded: false

restaurantData.loadRestaurants = ->
if !restaurantData.isLoaded
$http.get('./restaurants.json').success( (data) ->
restaurantData.data.restaurants = data
restaurantData.isLoaded = true
console.log('Successfully loaded restaurants.')
).error( ->
console.error('Failed to load restaurants.')
)
return restaurantData
])


Then I add this data in controller mainRestCtrl.js.coffee



---mainRestCtrl.js.coffee---
@RestCtrl = ($scope, $location, $http, restaurantData) ->

$scope.data = restaurantData.data

restaurantData.loadRestaurants()

console.log($scope.data)
...


If I watch console google chrome logs I get this data:



Object {restaurants: Array[1]}
restaurants: Array[36]
0: Object
1: Object
2: Object
...
33: Object
34: Object
35: Object
length: 36


If I add length



console.log($scope.data.length)             \get in console undefined
console.log($scope.data.restaurants.length) \get in console only 1 restaurant with
title: 'Loading'


How to get length equal 36 restaurants? Thanks for advice!



UPD solution



---mainRestCtrl.js.coffee---
...
restaurantData.loadRestaurants().then (res) ->
$scope.rests = res
console.log($scope.rests.data.length) \console log chrome return 36
return
...

More From » json

 Answers
3

I don't know coffee script, but you need to wait for the promise to be resolved.
I guess that it should look something like this:



restaurantData.loadRestaurants().then(res -> console.log(restaurantData.data.length));


Pure Js:



restaurantData.loadRestaurants().then(function(res){console.log(restaurantData.data.length)});

[#43571] Friday, July 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalistaz

Total Points: 0
Total Questions: 100
Total Answers: 106

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;