2016-10-07 9 views
0

ボタンを使用して読み込まれたデータを更新するメソッドを追加する際に問題があります。 マイコントローラー:AngularJS Reloadボタン?

.controller('mainCtrl', function($scope, $http, User) { 
     $scope.loading = true; 

     User.get() 
      .success(function(data) { 
       $scope.users = data; 
       $scope.loading = false; 
      }); 
    }); 

サービス:

angular.module('userService', []) 

    .factory('User', function($http) { 

     return { 
      get : function() { 
       return $http.get('/api/users/get'); 
      } 
     } 

    }); 

そして、これが私の見解はどのように見えるかです:あなたがそこに見ることができるよう

<div class="box" ng-app="userApp" ng-controller="mainCtrl"> 
       <div class="box-header"> 
        Angular Test <button class="btn btn-success" ng-click="get()"><i class="fa fa-refresh"></i> Reload</button> 
       </div> 
       <div class="box-body"> 
        <p class="text-center" ng-show="loading"><span class="fa fa-meh-o fa-5x fa-spin"></span></p> 
        <table ng-hide="loading" class="table table-responsive"> 
         <thead> 
          <tr> 
           <th>ID</th> 
           <th>Username</th> 
           <th>Realname</th> 
           <th>Email</th> 
           <th>Phone</th> 
           <th></th> 
          </tr> 
         </thead> 
         <tbody> 
          <tr ng-repeat="user in users"> 
           <td>@{{ user.id }}</td> 
           <td>@{{ user.name }}</td> 
           <td>@{{ user.realname }}</td> 
           <td>@{{ user.email }}</td> 
           <td>@{{ user.phone }}</td> 
           <td> 
            <a href="/admin/profile/@{{ user.id }}" class="btn btn-block btn-primary btn-sm"> 
             <i class="fa fa-user" aria-hidden="true"></i> Profile 
            </a> 
           </td> 
          </tr> 
         </tbody> 
        </table> 
       </div> 
      </div> 

、私はリロードボタンを持ってしようとしていますng-click="get"を使用しています。しかし、これは何もしません。そこに電話する必要がありますか?

+0

ng-hide/ng-showの代わりにng-ifを試して、$ scope.loading = trueをfalse、$ scope.loading = falseをtrueに置き換えることはできますか? コントローラ内のすべてのデータを取得しましたか?あなたはconsole.logでチェックしましたか? – Wandrille

+0

データの読み込み中です。ボタンがリロードを開始していないことだけです。 – Scarwolf

+0

申し訳ありませんが、私は見ていません。あなたの関数はどこで定義されていますか?それはあなたのコントローラーで定義されています。 – Wandrille

答えて

3

ユーザーデータを取得してスコープに割り当てるには、コントローラで新しい関数を作成する必要があります。この方法で、テンプレートから呼び出すことができます。

.controller('mainCtrl', function($scope, $http, User) { 


    function get() { 
     $scope.loading = true; 
     User.get() 
      .success(function(data) { 
       $scope.users = data; 
       $scope.loading = false; 
      }); 
    } 

    // Assign the get function to the scope 
    $scope.get = get; 

    // Call the get function when the controller is created 
    get(); 
}); 
+0

が恐ろしいことを見ることができます、これは期待どおりに動作します。どうもありがとうございました。 – Scarwolf

+0

'$ scope.user'は機能しません。チュートリアルからそれを取った。私はそれはユーザー** sと思う**ビューのループのため:? ' – Scarwolf

+0

申し訳ありませんが、 – nagyf