2017-08-10 60 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; 
    }); 
});