how can refresh my scope after ajax call

2019-09-08 01:11发布

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.

2条回答
手持菜刀,她持情操
2楼-- · 2019-09-08 02:04

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

查看更多
欢心
3楼-- · 2019-09-08 02:10

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
   });
}
查看更多
登录 后发表回答