简体   繁体   English

如何获取length scope.data angularjs?

[英]How to get length scope.data angularjs?

I want to get length my json date. 我想获取我的json日期的长度。 I have service whose take date json from http url. 我有从http url获取日期json的服务。 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中

---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: 如果我观看控制台google chrome日志,则会得到以下数据:

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? 如何获得相等于36个餐厅的长度? Thanks for advice! 谢谢你的建议!

UPD solution UPD解决方案

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

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: 纯Js:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM