Pim
Pim

Reputation: 876

Why is the view not updating in this particular case? ($scope.$apply)

Just trying to understand why in this case I would need to use $scope.$apply ? According to all the info I've read about the subject, I shouldn't have to, since everything is happening inside Angular? What am I missing?

In my controller:

$scope.savePreset = function(columns, $event){
  $event.preventDefault();
  preset.name = prompt("Please enter preset name", "My Preset");
  if (preset.name != null) {
    preset.columns = $scope.columns;
    $scope.presets[preset.name] = preset; // (Object)
    // Without $scope.$apply() here, view isn't updated. Why?
    alert('Your preset "' + preset.name + '" has been saved.');
    $scope.loadPreset(preset.name);
  } else {
    alert('Please enter a valid name.');
  }
}

(the savePreset function is called in an ng-click directive, and there's an ng-repeat for preset in presets, which isn't updating).

Thanks, Pim

Upvotes: 4

Views: 87

Answers (2)

Narek Mamikonyan
Narek Mamikonyan

Reputation: 4611

as mentioned in comment @Sergiu Paraschiv using functions which wrapped in window was stopping angular $digest cycle that's why my advise is to use $window provider and $window.prompt and $window.alert functions I think they are will work

here is a example

Upvotes: 3

Abdoul Sy
Abdoul Sy

Reputation: 590

~Prompt, alert.. will pause the execution of code (blocks the thread), to prevent the likes of setInterval, setTimeout to go crazy .

The $digest loop is made up of two smaller loops: when you do a prompt. $evalAsync is used, and the code inside is executed outside angular.This is usually done with setTimeout(0).

So In one sentence: this is prompt's fault, you might be better off with a widget that does the same thing.

Edit: Sorry submitted to fast: here is the original answer: Error: $digest already in progress in angularjs when using alert

Upvotes: 1

Related Questions