Ruslan
Ruslan

Reputation: 91

Angular and jQuery Ajax Request

I have some problems with Angular and jQuery that does an http call to api in rest in an a WebServlet. I would like print result of request in HTML Page with ng-show but, I can't- This is my controller:

var myApp = angular.module('spicyApp1', []);
myApp.controller('SpicyController', ['$scope', function($scope) {
    $scope.chiliSpicy = function() {
    var url = "http://localhost:8080/RESTnt/";
    var user = "admin";
    var pwd = "password";
    $.ajax({
        type: 'GET',
        url: url + 'login?username='+user+'&password='+pwd,
        dataType: 'xml',
        success: function(data)
            {
                $scope.result = true;
            },
        error: function (data) 
            {
                $scope.result = false;
            },
        async:true
        });
    };
}])

and this is my html

<html>

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>


</head>
<body ng-app="spicyApp1">
<div ng-controller="SpicyController">
 <button ng-click="chiliSpicy()">Chili</button>
 <p>The food is {{spice}} spicy!</p>
 <p ng-show="result===200" class="alert alert-warning">Your guess is higher.</p>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.js"></script>
<script src="ajaxQuery.js"></script>
</body>
</html>

Upvotes: 1

Views: 6331

Answers (2)

pavithra
pavithra

Reputation: 1

Inside ajax call success, write the following code:

$scope.$apply(function () {
    $scope.result = true;
});`

Upvotes: 0

Numyx
Numyx

Reputation: 1758

You should avoid mixing jQuery methods and AngularJS methods. Angular has its own ajax service called $http, which you could use:

myApp.controller('SpicyController', ['$scope', '$http', function($scope, $http) {
    $http.get(url + 'login?username='+user+'&password='+pwd).success(function(data) {
        $scope.result = true;
    })
}

If you insist on using jQuery ajax, you can do this by adding a $scope.$apply() to you response callbacks:

    success: function(data)
        {
            $scope.result = true;
            $scope.$apply();
        },
    error: function (data) 
        {
            $scope.result = false;
            $scope.$apply();
        },

This is required to tell angular that the scope has been changed and to run the digest cycle which will check the HTML DOM for changes.

Upvotes: 1

Related Questions