2015-07-03 60 views
1

我想在默认的离子模板(选项卡)中做同样的例子。如果您有一个名为的聊天室聊天,它包含一串带说明的图片,当您点击列表中的其中一个项目时,您将获得更多详细信息。并且所有这些都是使用预定义的数组(硬编码)完成的。Angular/Ionic聊天的例子?

在我的情况我试图做同样的事情,但用一个json数组来保存来自远程数据库的值。我在service.js文件中定义了工厂来执行此操作。但是,因为我使用$ http调用异步请求,所以返回的json数组将不会立即保存这些值(它需要时间),并且这会导致从工厂返回的数组为空。

我厂是这样的:

.factory('GCs', ['$http', function($http) { 
    // this is the var that I want to pass to get method 
    //but it will be empty because the get method in the return section will be executed before the call finished. 
    var obj = {}; 

    $http.post("mydomina.com?myrequest=getbyid", { 
      "id": "1" 
     }) 
     .success(function(data) { 
      obj = data; //there is a data returned correctly from the db 
     }) 
     .error(function(data, status, headers, config) { 
      //TODO something.. 
     }); 

    console.log(obj); //obj is undefined? 

    return { 
     all: function() { 
      return obj; //obj is empty here!! 
     }, 
     get: function(gcId) { 
      for (var i = 0; i < gcs.length; i++) { 
       if (gcs[i].id === parseInt(gcId)) { 
        return gcs[i]; 
       } 
      } 
      return null; 
     } 
    }; 
}]); 

然后在控制文件中,我有我自己的控制器,对于所有调用该工厂/得到像下面的方法。

.controller('DashCtrl', function($scope, GCs) { 
    console.log(GCs.all());// it is giving me undefined 
    $scope.GCResult = GCs.all(); //GCResult is empty and thereby no data will be displayed when I pass the scope to the view. 
}) 

.controller('GCDetailCtrl', function($scope, $stateParams, GCs) { 
    $scope.item = GCs.get($stateParams.GC_ID); 
}) 

我需要你的帮助。

回答

1

可以返回的承诺,$http.post()产生(docs

.factory('GCs', ['$http', function($http) { 
     return { 
      getById: function(id) { 
       return $http.post("mydomina.com?myrequest=getbyid", { "id": id }); 
      } 
     }; 
}]); 

,改变你的控制器

.controller('DashCtrl', function($scope, GCs) { 

    $scope.getData = function(id){ 
     GCs.getData(id) 
      .success(function(data){ 
       console.log(data); 
       $scope.GCResult = data; 
      }); 
    }; 
}) 

,它应该是工作的罚款

+0

我会试试.. – Riad

+0

你是对的!现在如何解决问题的第二部分,其中项目列表中的每个项目都有其自己的细节。看看我对我的问题所做的修改。基本上我想在返回部分使用get方法,从而形成ID我可以显示已编辑的单击项目 – Riad

+0

的详细信息。这个想法是,你可以从你的html代码中调用'getData(id)'(这个id是当前迭代项的匹配ID) –

0

的承诺返回从$http不能直接约束:

.factory('GCs', ['$http', function($http) { 
    return { 
    all: function() { 
     return $http.post("mydomina.com?myrequest=getbyid", { "id": "1"}); 
    } 
    }; 
}]); 

在承诺的角1.2自动解包已被删除。请参阅http://docs.angularjs.org/guide/migration#templates-no-longer-automatically-unwrap-promises

+0

我试过这种方法。它没有工作,并没有在同一时间给我一个错误。 我需要这个异步请求的数据 – Riad