将数据从 Angular 1.x 工厂发送到 Angular 1.x 控制器

Sending data from Angular 1.x Factory to Angular 1.x controller

我定义了一个与数据库相关的服务queries/updates。我已经定义了控制器,它通过从服务中获取对象来对 angular 元素进行数据解析。我想让每个范围都不同

如何使用 ngResource 将数据从服务传递到控制器。

示例服务:

app.factory("ioHomeService", ["$rootScope","$resource", function($rootScope,$resource) {
   var svc = {};
   var home = $resource('/home/getAll');
   var dbData= home.get();
   svc.getRooms = function() {
       return dbData;
   };
    return svc;
}]);

示例控制器:

app.controller("homeCtrl",["$scope","$mdDialog","ioHomeService",function($scope,$mdDialog,ioHome){
    $scope.dbData = ioHome.getRooms();
    //Here UI specific objects/data is derived from dbData
}]);

在查询 DB 并且结果可用后,服务中的 dbData 反映了来自 DB 的数据,但是 Controller 无法获取该数据

您必须 return 服务对象,如下所示:

app.factory("ioHomeService", ["$rootScope","$resource",   function($rootScope,$resource) {
var svc = {};
var home = $resource('/home/getAll');
var dbData= home.get();
svc.getRooms = function() {
   return dbData;
};
return svc; //here
}]);

目前 getRooms 方法对您的控制器不可见。

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

来自 https://docs.angularjs.org/api/ngResource/service/$resource

由于在 $resource 返回数据之前调用了 'ioHome.getRooms();',您得到的 dbData 是一个空引用

app.factory("ioHomeService", ["$rootScope","$resource", function($rootScope,$resource) {
   var svc = { 
     dbData : {}
   };
   var home = $resource('/home/getAll');
   var svc.dbData.rooms = home.get();
   return svc;
}]);

控制器

app.controller("homeCtrl",["$scope","$mdDialog","ioHomeService",function($scope,$mdDialog,ioHome){
    $scope.dbData  = ioHome.dbData;

    //You can access the rooms data using $scope.dbData.roooms

    //Here UI specific objects/data is derived from dbData
}]);