Marko
Marko

Reputation: 128

Angular $timeout doesn't update the view

In my controller I have a method that sends a POST request to my REST API. On success/error I want to display an success/error message using ng-show. The problem is that my scope variable is changed but my view is not being updated. I have tried using $scope.$apply() but that throws $digest error. Below is my current code. Any ideas?

 function AdminController($scope, $http, $timeout) {
    $scope.addUserError = false;
    $scope.addUserSuccess = false;

    $scope.createUser = function (newuser) {
        $http.post("rest/user", JSON.stringify(newuser)).success(function () {
            console.log("User added");
            $timeout(function () {
                $scope.addUserSuccess = true;
                $scope.addUserError = false;
            });
        }).error(function () {
            $timeout(function () {
                $scope.addUserSuccess = false;
                $scope.addUserError = true;
                console.log($scope.addUserError); //true
            });
        })
    }
    }

Upvotes: 0

Views: 607

Answers (1)

nweg
nweg

Reputation: 2865

Update your code to the following:

function AdminController($scope, $http, $timeout) {
    $scope.addUserError = false;
    $scope.addUserSuccess = false;

    $scope.createUser = function (newuser) {
        $http.post("rest/user", JSON.stringify(newuser)).success(function () {
            $scope.addUserSuccess = true;
            $scope.addUserError = false;
        }).error(function () {
            $scope.addUserSuccess = false;
            $scope.addUserError = true;
        });
    };
}

Your view should look something like this:

<div ng-show="addUserSuccess">User Added!</div>
<div ng-show="addUserError">Error adding user</div>

You don't need to use timeout here. This is just a simple model update and angular will do this for you inside the $http call automatically.

Upvotes: 2

Related Questions