Sridhar Paiya
Sridhar Paiya

Reputation: 478

Data bind works only on second click event

I have a click event to call the AngularJS function which retrieves the data from SQL and return to the ajax call. My problem is the data which is retrieved binds with ng-repeat only on the second click event.Here is my code,

`

(function (app) {
    app.controller("OnvioController", function ($scope,$http, OnvioService) {
        $scope.retData = [];
        $scope.getResult = function () {

            var serviceURL =window.location.origin+ '/Datafetching/dataFetch';

            $.ajax({
                type: "POST",
                url: serviceURL,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data, status) {
                    $scope.retData = data;
                },
                error: function (status) {

                }
            });
        }

    });
}(angular.module("OnvioModule")));

`

Upvotes: 0

Views: 615

Answers (3)

Karan Patel
Karan Patel

Reputation: 2289

Do not use $.ajax in angularJS.

You can do this by $http.get

I haven't tried it my self right now. but it should work in your case.

(function (app) {
    app.controller("OnvioController", function ($scope,$http, OnvioService) {
        $scope.retData = [];
        $scope.getResult = function () {

            var serviceURL =window.location.origin+ '/Datafetching/dataFetch';

            $http.get(serviceURL).success( function(response) {
                $scope.retData = response; 
            });
        }

    });
}(angular.module("OnvioModule")));

refer this document for more details

Upvotes: 3

Hemant Malpote
Hemant Malpote

Reputation: 891

Add a $scope.$apply() in your success function.

Upvotes: -1

Walfrat
Walfrat

Reputation: 5353

Use $http.post instead of $.ajax.

If you still want to use $.ajax add a $scope.$apply() in your success function. This will trigger angular loop to search for changes outside of his context. This is because $.ajax is executing outside of angular stuff.

Upvotes: 1

Related Questions