1

Hie I am new to Angular and I'm trying to change (or set) the scope variables from a function that is inside a controller. Here is my code:

$.ajax({
        type: "POST",
        url: URL,
        data: param = "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: successFunc,
        error: errorFunc
    });

    function successFunc(data, status) {
            $scope.modalStatus = 'success';
            $scope.modalIcon = 'check';
            $scope.modalMessage = 'Invoice Saved!';
            showNotification();
    }

    function errorFunc() {
        alert('error');
    }

$scope.modalStatus, $scope.modalIcon and $scope.modalMessage are the scope variables that were set earlier at the beginning of the controller. How do I change them in that successFunc method, please help.

5
  • 2
    Possible duplicate of Why angular data-binding not working with jquery ajax? Commented Jan 31, 2016 at 0:30
  • Angular provides a $http service to do ajax calls. You would be far better off using that instead of jQuery. Commented Jan 31, 2016 at 0:34
  • woow thank @AlonEitan, that solved my problem! Commented Jan 31, 2016 at 0:35
  • thanks @Rhumborl, I will try that as well Commented Jan 31, 2016 at 0:36
  • @EMahaso You're welcome, FYI - what @Rhumborl wrote is the best solution for this, don't just jQuery's ajax, use angular's $http instead Commented Jan 31, 2016 at 0:37

2 Answers 2

4

Change your success callback:

function successFunc(data, status) {
  $scope.modalStatus = 'success';
  $scope.modalIcon = 'check';
  $scope.modalMessage = 'Invoice Saved!';
  showNotification();
  $scope.$apply();
}

Also it's a bad practise to use jQuery and Angular in one application. Angular provides $http fo requests.

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

Comments

0

Why use Jquery $ajax while AngularJs provides $http.

Actually, there is an internal mechanism in AngularJs to apply changes, call it $digest. When you use JQuery, it is beyond angularJs scope and it does not apply $digest mechanism.

so in this case manually apply $digest by using following apply method inside successFunc function.

$scope.$apply(function() {
  $scope.modalStatus = 'success';
  $scope.modalIcon = 'check';
  $scope.modalMessage = 'Invoice Saved!';
});

this link may help you understanding more about $apply and $digest http://www.panda-os.com/2015/01/angularjs-apply-digest-and-evalasync/#.Vq1Z2lN95R0

Comments

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.