Sameek Mishra
Sameek Mishra

Reputation: 9384

how can refresh my scope after ajax call

I am newbie for angularjs.I have list of persons and each person have edit and delete button. when i click to edit button ng-dialog box was open and show person details and person can change and save information on database,behind save button ajax call trigger and update information on database.

Updating information on database work well but on UI side my view doesn't reflect my database changes. I had tried to apply "$scope.$apply();" method but i got error message "$digest already in progress".

Please help me,how can refresh my scope after ajax call.

Upvotes: 0

Views: 7952

Answers (2)

Abel Rodríguez
Abel Rodríguez

Reputation: 111

Try with $scope.$digest(); or use $http instead jQuery ajax or others

Upvotes: 3

Artyom Pranovich
Artyom Pranovich

Reputation: 6962

You can use shared service for that and broadcast any event through this service. Broadcasted event can be listened in any controller with $scope.$on.

For example:

angular.module("app", []).factory("sharedService", function($rootScope){

    var mySharedService = {};

    mySharedService.values = {};

    mySharedService.personWasUpdated = function(){
        $rootScope.$broadcast('update');
    }

    return mySharedService; 
});

Ctrl for person editing.

app.controller('personEditController', ['$scope', 'sharedService', '$http', function ($scope, sharedService, $http) {
   $scope.updatePerson = function(newPerson){
       $http.post("../some URL/..", {person: newPerson})
          .success(function(data){
             sharedService.personWasUpdated(); //event broadcasing
          })
   };
}

Ctrl for displaying list of persons.

app.controller('personController', ['$scope', 'sharedService', '$http', function ($scope, sharedService, $http) {
   var loadPersonsData = function(){
      $http.get("../some URL/..").
         .success(function(data){
            $scope.persons = data;
         })
   };
   loadPersonsData(); //first load

   $scope.$on('update', function () {
      loadPersonsData(); // load after update of any person
   });
}

Upvotes: 3

Related Questions