0

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
            });
        })
    }
    }
3
  • 1
    You dont need timeout - $http will trip a $digest cycle - are there any errors in your call? Commented Mar 3, 2015 at 17:29
  • One of the tenants of angular is to always put your properties in an object under $scope. So instead of $scope.addUserSuccess you'd have $scope.model.addUserSuccess. Sometimes this is all you need to fix something like this. Commented Mar 3, 2015 at 17:29
  • @tymeJV no errors. I put error {{addUserError}}<br> success {{addUserSuccess}}. It is being shown correctly. Commented Mar 3, 2015 at 17:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You and tymeJV were both correct. Although my error was also that I had ng-show={{addUserSuccess}}. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.