2017-08-10 9 views
0

私はAngularJsを初めて使いました。工場のモジュールで$ scopeを使わなければ少し問題があります。工場からのAngularJsデータバインディング

私は工場からコントローラで使用されているGET関数を持っています。これはdbからリストを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

ごめんなさい:データを抽出するために.thenメソッドを使用して、コントローラで

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; }); } }); 

をしかし、それはちょっと混乱しているようです。どのようにオブジェクトはhtml var 'allRows'にバインドされますか? –

+0

コードを編集しました。コントローラコードをチェックしてください。 – Rishi

+0

申し訳ありませんが、うまくいきましたが、私はそれを呼び出さずに自動的に機能を実行します。それを管理する方法はありますか? –

0

で、HTTPの約束を返す:

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

    var promise = appServices.getAllRows(); 

    promise.then(function(allRows) { 
     $scope.allRows = appRows; 
    }); 
}); 
関連する問題