【问题标题】:angularjs get data from Json using $resourseangularjs 使用 $resource 从 Json 获取数据
【发布时间】:2015-03-13 19:07:29
【问题描述】:

下午好!学习 Angularjs。下面是项目的结构。 我有一个从 json 读取数据的服务

var WebKrServices = angular.module('WebKrServices', ['ngResource']);

WebKrServices.factory('DataPlant', ['$resource',
  function($resource){
    return $resource('plants/:plantId.json', {}, {
      query: {method:'GET', params:{plantId:'plants'}, isArray:true}
    });
  }]);

和控制器

var WebKrControllers = angular.module('WebKrControllers', []);

WebKrControllers.controller('PlantsCtrl', ['$scope', 'DataPlant',
  function($scope, DataPlant) {
    $scope.plants = DataPlant.query();
  }]);

将这些信息传递给html

<div ng-repeat="plant in plants">
  <h2 class="text-center">{{plant.name}}</h2>
  <a href="#/plants/{{plant.id}}"></a>
</div>

事实上,问题。在 html 中我看到来自 json 的数据,而控制器在访问植物时看到一个空对象?

for (var p in plants) {
  . . .
}

如何从控制器中的植物中获取数据?

谢谢大家的回答。

【问题讨论】:

    标签: json angularjs get resources


    【解决方案1】:

    因为它是异步调用。在$scope.plants = DataPlant.query(); 之后,植物保持未定义,直到数据到达(嗯,它并不完全未定义,您可以在调试器中检查它)。当数据到达时 - $scope.plants 得到解决并且 html 被更新。要在数据到达后运行一些代码,请使用回调:

    $scope.plants = DataPlant.query(function(response) {
            console.log($scope.plants);
    }, function (response) {
            console.log('Error');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多