简体   繁体   中英

Changing AngularJS scope variables from an inside function

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM