Tharanga Tharanga - 6 months ago 32
AngularJS Question

After make ajax-post request the html elements are not refresh in angular

I have a issue.i make ajax-post request then it execute properly then i get the response.After process the response i need again make ajax-get then those data i set to a variables in the scope.the data are successfully assign in to variable but html elements are not refresh.this is the sample code.

this is html part

<div ng-controller="AppManagerCtrl" >
<md-list-item ng-repeat="app in apps">
<div>
<div flex="20" layout-padding>
<p>{{app.appId}}</p>
</div>
<div flex="20" layout-padding>
<p>{{app.appName}}</p>
</div>
</md-list-item>
</div>


this the angular service

app.service('AppManagerService',function($http){

this.loadApps = function(){
var request = $http.get('apps');
return request.then(handleSuccess,handleError);
};

this.submitApp = function(){
var request = $http.post('apps',
$('#newAppDetail').serialize(),
{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
);

return request;
};

function handleError(responce){
console.log(responce);
}

function handleSuccess( response ) {
return response.data.value;
}

});


this the angular controller

app.controller('AppManagerCtrl', function($scope,$mdDialog,$mdMedia,AppManagerService) {

function loadApps(){
AppManagerService.loadApps().then(function(apps){
$scope.apps = apps;
console.log($scope.apps);
}
);
}

loadApps();

$scope.submitNewApp = function(){

AppManagerService.submitApp().then(function(responce){
var data = responce.data;
if(data.status == 1){
loadApps();
}
});

};

});


all these are in the html body.from the begin html part then angular service and finally controller.

Answer

The result of an ajax call isn't monitored by Angular, which is why your scope isn't updated (it will be on the digest though).

To solve this, you must manually call $scope.apply().

However, if another digest is already in progress, it will throw an error. So it's safer to use the $timeout utility:

function loadApps(){
    AppManagerService.loadApps().then(function(apps){

        $timeout(function() {

           // update your scope variables here. The refresh will occur automatically.

            $scope.apps = apps;
            console.log($scope.apps);

        });

    });
}
Comments