为什么我的视图数据不在我的视图中填充?

时间:2014-05-06 03:02:50

标签: ruby-on-rails angularjs ruby-on-rails-4

几天前,我开始学习AngularJS(独立和轨道)。我有以下控制器,服务和视图设置。根据我的console.log消息,我的数据似乎成功加载,但我的视图只是空白。我知道视图是有用的,因为我用静态的哈希数组测试它,可以看到数据很好。请问有人可以解释一下吗?此外,我从一个单独的(本地)应用程序中提取数据。我很感激能得到的所有帮助......谢谢

agenciesCtrl.js.coffee

@AgenciesCtrl = ($scope, Agency) ->
  $scope.agencies = Agency.all
return Agency

agency.js.coffee

angular.module('app').factory('Agency', ['$http', ($http) ->

  loadAgencies = () ->
    $http.get("http://localhost:3001/agencies")
    .success((data) ->
      console.log "Agencies successfully retrieved from server"
      console.log data
      return data
    ).error ->
      alert "error"
    return

  agencies = loadAgencies()

  Agency = 
    all: agencies
    create: ->
      console.log "CREATE"
      return
    find: ->
      console.log "FIND"
      return
    delete: ->
      console.log "DELETE"
    return

  return Agency

])

的index.html

<div class="container " style="margin-top: 40px">
  <div class="col-xs-12">
    <div class="row" ng-repeat="agency in agencies">
      <h2><a ng-click="">agency name: {{ agency.name }}</a></h2>
    </div>
  </div>
</div>

控制台日志:

Agencies successfully retrieved from server
[Object, Object, Object, Object]
  0: Object
  1: Object
  2: Object
  3: Object
  length: 4
  __proto__: Array[0]

3 个答案:

答案 0 :(得分:0)

好吧,你的loadAgencies方法没有填充数组,它只返回任何内容。也许你应该从服务器返回data,如:

loadAgencies = () ->
  $http.get("http://localhost:3001/agencies")
  .success((data) ->
    console.log "Agencies successfully retrieved from server"
    console.log data // this line
    return data
  ).error ->
    alert "error"
  return

答案 1 :(得分:0)

不确定你是如何完成作业的,而不是做

agencies = loadAgencies()

如果你这样做

 .success((data) ->
      console.log "Agencies successfully retrieved from server"
      console.log data
      agencies=data;  //Assigning agencies here
      return data;

它应该有用。我在你的代码中看到的回报从成功回调中返回,而回调并没有分配给代理商。

答案 2 :(得分:0)

问题在于: $http.get返回一个promise,而不是成功回调中返回的实际值。

因此,您必须为then回调提供承诺并分配值。 (如果在promise中返回一个值,它将作为参数在下一个promise中提供)

angular.module('app').factory('Agency', ['$http', ($http) ->  
  Agency = 
    all: -> 
     $http.get("http://localhost:3001/agencies")
       .success((data) ->
        console.log "Agencies successfully retrieved from server"
        console.log data
        return data; //this won't give the the value as an return value!! careful
       )
       .error ->
        alert "error"
    create: ->
      console.log "CREATE"
      return
    find: ->
      console.log "FIND"
      return
    delete: ->
      console.log "DELETE"
    return

  return Agency

])

用法然后(coffeescript中的dunno):

Agency.all().then((agencies) ->
  $scope.agencies = agencies
)