【问题标题】:how to pass data from ngresource factory to controller?如何将数据从 ngresource 工厂传递到控制器?
【发布时间】:2017-06-10 10:04:56
【问题描述】:

我有一个使用 $resource.get 请求返回 JSON 对象的工厂,但我无法从我的 ngresource 工厂获取一些数据:

HTML

<body ng-app="myApp" ng-controller="myCtrl" >
<table border="1">
    <tr>
        <th>Name</th>
        <th>city</th>
    </tr>
    <tr ng-repeat="x in data.records">
        <td style="padding: 20px">{{records.Name}}</td>
        <td style="padding: 20px">{{records.City}}</td>
    </tr>
</table>
</body>

JS:

angular.module('myApp',['ngResource']);

angular.module('myApp').controller("myCtrl",function (yourService,$scope) {

});

angular.module('myApp').

factory('yourService', ["$resource", function($resource,$scope){

    return $resource("http://www.w3schools.com/angular/customers.php").get().$promise
        .then (function (data){


    });
    return data;
}]);

【问题讨论】:

标签: angularjs


【解决方案1】:

把你的工厂改成

factory('yourService', ["$resource", function($resource, $scope) {
  return $resource("http://www.w3schools.com/angular/customers.php").get().$promise
    .then(function(data) {
       return data;
    });
}]);

然后在你的控制器内部获取数据:

yourService.then(function(data) {
  console.log(data.records);
});

fiddle

【讨论】:

    【解决方案2】:

    您的退货数据位置不正确。在内部响应中返回数据。

      factory('yourService', ["$resource", function($resource) {
      return $resource("http://www.w3schools.com/angular/customers.php").get().$promise
        .then(function(data) {
           return data;
        });
    }]);
    

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 2015-09-07
      • 1970-01-01
      • 2014-07-29
      相关资源
      最近更新 更多