how can refresh my scope after ajax call

回眸只為那壹抹淺笑 提交于 2020-01-17 03:55:08

问题


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.


回答1:


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
   });
}



回答2:


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



来源:https://stackoverflow.com/questions/27397360/how-can-refresh-my-scope-after-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!