2016-10-07 2 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

죄송합니다, 그 ng-repeat를 간과했습니다. – nagyf