niftygrifty
niftygrifty

Reputation: 3652

AngularJS: No view changes even when using $apply()

The delete functionality in this AngularJS apps for the most part (record is deleted and success message is displayed), but the view doesn't update.

I've tried adding $scope.$apply() but that only gives me a $digest already in progress error. But if the digest is in progress, shouldn't that update the view? Isn't that what digest does?

In the view:

<button ng-click="deleteNote(note)">Delete</button>

In the controller:

LessonNotes.controller("NotesCtrl", ["$scope", "$routeParams", "$location", "Note", "NoteType", "Alert",
  function($scope, $routeParams, $location, Note, NoteType, Alert) {

    $scope.notes = Note.query();

    $scope.deleteNote = function(note) {
      if(confirm("Are you sure you want to delete this note?")) {
        note.$destroy(
          function(n, responseHeaders) {
            $scope.$apply();
            Alert.add("success", "Note deleted successfully!", 5000);
          },
          function() {
            Alert.add("warning", "There was an error deleting the note!", 5000);
          }
        );
      }
    };

}]);

And the service:

LessonNotes.factory("Note", ["$resource", function($resource) {
  return $resource("lesson_notes/notes/:id", { id: "@id" }, {
    query: { method: 'GET', params: {}, isArray: true },
    update: { method: 'PATCH' },
    destroy: { method: 'DELETE' }
  });
}]);

In case it matters, I'm using Rails for the backend.

Upvotes: 1

Views: 42

Answers (1)

sfletche
sfletche

Reputation: 49714

To prevent the $digest already in progress error, try running your code within Angular's $timeout function.

Also, you are not using $scope.$apply properly, you want to wrap the $apply call around your code like this.

$timeout(function() {
    $scope.$apply(function() {
        note.$destroy...
    });
});

Upvotes: 1

Related Questions