Scarwolf Scarwolf - 1 month ago 9
AngularJS Question

AngularJS Reload button?

I have a problem with adding a method to refresh loaded data using a button.
My Controller:

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

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


Service:

angular.module('userService', [])

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

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

});


And this is how my view looks like:

<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>


As you can see there, I tried to have a reload button which is using
ng-click="get"
. However this does nothing. What do I need to call there?

Answer

You have to create a new function in the controller to get the user data, and assign it to the scope, this way you can call it from the template as you wanted.

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