Skip to content Skip to sidebar Skip to footer

Angular Page Doesn't Refresh After Data Is Added Or Removed

I'm having a recurrent problem with my angular app whereby it doesn't refresh the page after data has been added, edited or removed. So if I add a new item to a list of subjects, t

Solution 1:

Some times you need to apply changes to scope this is done by the following code:

$scope.$apply();

But this can be done only if it's not in "$digest" phase, otherwise it will throw exception. So you need to check first it's not in "$digest" phase then you can apply it. Here is the example of the code I use for safe applying changes:

safeApply: function (scope, callback) {
   if (scope.$$phase != '$apply' && scope.$$phase != '$digest' &&
        (!scope.$root || (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest'))) {
        scope.$apply();
    }
    if (angular.isFunction(callback)) {
        callback();
    }
}

Solution 2:

I can suggest next way:

You can't get data from database, after adding, you can easly push new added object to $scope.items.

Example:

$scope.add = function (newItem) {
        DataService.addItem(newItem).then(function(){
           $scope.items.push(newItem);
           //or for removing//$scope.items.splice($scope.items.indexOf(newItem), 1);
        });
    };

And adjust your factory:

   addItem: function (newProject) {
        $http.post('Api/Controller/Post').then(function(successResult){ 
             ...
        }, function (errorResult) {
           ...
        });
    }

Item will be added in $scope.items only after success calling of server-side method.

Solution 3:

Changing the structure of the requests slightly fixed the problem- so instead of

$scope.updateSubject = function () {
    SubjectFactory.update($scope.subject);
    $location.path('/subjects/');
    $scope.subjects = SubjectsFactory.query();
    $route.reload();
};

It is now

$scope.updateSubject = function () {
                SubjectFactory.update($scope.subject).$promise.then(function (subject) {
                    $scope.subject = subject;
                    $location.path('/subjects/');
                    $route.reload();
                }, function (err) {
                    console.error(err);
                });
            };

Post a Comment for "Angular Page Doesn't Refresh After Data Is Added Or Removed"