如何获取length scope.data angularjs?

时间:2014-07-26 20:59:22

标签: javascript json angularjs

我希望得到json约会的长度。我有来自http url的服用日期json的服务。代码如下所示:

---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    
])

然后我在控制器mainRestCtrl.js.coffee中添加这些数据

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

  $scope.data = restaurantData.data

  restaurantData.loadRestaurants()

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

如果我观看控制台谷歌浏览器日志,我会收到以下数据:

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

如果我添加长度

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

如何获得长度相等的36家餐厅?谢谢你的建议!

UPD解决方案

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

1 个答案:

答案 0 :(得分:0)

我不知道咖啡脚本,但你需要等待承诺得到解决。 我猜它应该是这样的:

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

Pure Js:

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