wyc
wyc

Reputation: 55263

Neither $scope.$apply and $scope.$digest updates the objects

I'm sing the following ng-click function to create groups:

$scope.createGroup = function() {
  AV.Cloud.run('createUserGroup', {
groupName: $scope.initName
  }, {
success: function(result) {
  var data = JSON.parse(result);
  var json = {
    id: data.objectId,
    name: data.name,
    users: 0,
    createdAt: data.createdAt
  }
  $scope.groups.push(json);
  $scope.initName = "";
  $scope.$digest();
},
error: function(error) {
  alert(error.message);
}
  });

But then when I click the link to go to the group (which is in the same page) the group doesn't appear. I have to refresh the browser in order to make it appear. I tried $scope.$digest() and $scope.$apply() but they didn't solve the problem, only location.reload(); does.

Does AngularJS have another function to make an update or reload that might solve this problem?

EDIT:

This is how I'm displaying the group:

<div id="group-new" class="col-md-6">
  <h2>{{group.name}}</h2>
</div>

Upvotes: 0

Views: 45

Answers (3)

Danscho
Danscho

Reputation: 466

Maybe there is already a $digest cycle running?

Try $timeout (you have to inject it into to your controller): $timeout

success: function(result){
    // ...
    $timeout(function(){
        $scope.groups.push(json);
        scope.initName = "";
    });
}

Basically it delays the execution (in the above case: 0ms) of the inner function and triggers a new digest cycle with $apply. It does not create "$digest already in progress" errors because it starts a new digest after the running one is finished.

Upvotes: 0

interested
interested

Reputation: 324

How did you use $scope.$apply? Did you try?

success: function(result) {
    // ...

    $scope.$apply(function () {
        $scope.groups.push(json);
        $scope.initName = "";
    });
}

Upvotes: 1

Alex Santos
Alex Santos

Reputation: 2950

Have you tried wrapping it up in $scope.$apply, it should both apply the changes to your $scope and digest afterwards. Example:

$scope.createGroup = function() {
  AV.Cloud.run('createUserGroup', {
    groupName: $scope.initName
  }, {
    success: function(result) {
      var data = JSON.parse(result);
      var json = {
        id: data.objectId,
        name: data.name,
        users: 0,
        createdAt: data.createdAt
      }
      $scope.$apply(function() {
        $scope.groups.push(json);
        $scope.initName = "";
      });
    },
    error: function(error) {
      alert(error.message);
    }
  });

Upvotes: 2

Related Questions