2017-08-10 66 views
0

我是AngularJs的新手,我没有在工厂模块中使用$ scope的问题。AngularJs从工厂数据绑定

我有一个控制器通过工厂使用的GET函数,它应该从我的数据库返回一个列表作为json 并使用ng-repeat在html上显示它。由于我无法找到解决方案的原因,事实并非如此。我唯一的猜测是,从工厂到html的数据绑定存在问题。

如何将返回的json绑定到变量并将该变量绑定到我的html?

这个函数在我创建工厂之前就工作了,但是没有使用$ scope 我很迷茫。 我希望我能够正确解释自己。

厂:

(function() { 

    angular.module("myApp").factory('appServicesProvider',function($http) { 

    var restURL = "http://localhost:8080/Project/rest/api/"; 


    function getAllRows(allRows){ 

    $http.get(restURL).then(
      function(response){ 
       allRows = response.data.coupon; 
      } 
    ); 
} 

return{getAllRows:getAllRows} 

控制器:

(function() { 

    angular.module("myApp") 
    .controller("AdminController",function($scope, $http, 
    appServicesProvider) { 


    // I know that this method of scoping a service is not best and/or recommended, 
    //it just works better for me with the admin controller. 
    $scope.appServicesProvider = appServicesProvider; 

HTML:

<div id="getAllRowsDiv"> 

     <table class="table table-hover"> 
     <thead> 
      <tr> 
       // list details 

      <th></th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr ng-repeat="coupon in allRows"> 

      // list 

      </tr> 
     </tbody> 
    </table> 
    <button class="btn btn-success" ng- 
    click="appServicesProvider.getAllRows()" >Get All Rows</button> 
</div> 

回答

0

使用$ Q

(function() { 

    angular.module("myApp").factory('appServicesProvider',function($q, $http) { 

    var restURL = "http://localhost:8080/Project/rest/api/"; 


    function getAllRows(allRows){ 
    var deffer = $q.defer(); 
    $http.get(restURL).then(
      function(response){ 
       deffer.resolve(response.data.coupon;) 
      },function(error){ 
       deffer.reject(error) 
      } 
    ); 
    return deffer.promise 

} 

return{getAllRows:getAllRows} 

和控制器

$scope.getRows = function(){ 
    appServicesProvider.getAllRows().then(function(res){ 
      $scope.allRows = res; 
     },function(err){ 
      alert(err) 
     }) 
} 
$scope.getRows(); 
+0

对不起,但这似乎有点令人困惑。对象如何绑定到html var'allRows'? –

+0

我编辑了代码,请检查控制器代码。 – Rishi

+0

好吧,这工作,但现在它自动执行功能,而我没有调用它,有没有办法管理呢? –

0

在服务上,返回HTTP承诺:

app.factory('appServices',function($http) { 

    return { getAllRows:getAllRows } 

    var restURL = "http://localhost:8080/Project/rest/api/"; 

    function getAllRows(){   
     ͟r͟e͟t͟u͟r͟n͟ $http.get(restURL) 
      .then(function(response){ 
      var allRows = response.data.coupon; 
      ͟r͟e͟t͟u͟r͟n͟ allRows; 
     }); 
    } 
}); 

在控制器方面,利用.then方法来提取数据:

app.controller("AdminController",function($scope, $http, appServices) { 

    var promise = appServices.getAllRows(); 

    promise.then(function(allRows) { 
     $scope.allRows = appRows; 
    }); 
});