S
S
Svyatoslav Khusamov2017-01-09 13:12:00
Angular
Svyatoslav Khusamov, 2017-01-09 13:12:00

What is the correct way to write a button visibility function in Angular 1 without causing an infinite $digest loop?

I have a button in my view template:

<button ng-show="buttonAddFriendVisibled()">Добавить в друзья</button>

It should be visible if the buttonAddFriendVisibled() function returns true. This function is described accordingly in the view controller:
// Определение видимости кнопки Добавить в друзья
$scope.buttonAddFriendVisibled = function() {
  return (
    $scope.authenticated.hasFriend(user)
      .then(function(hasFriend) { 
        return $scope.user.id != $scope.authenticated.id && !hasFriend; 
      })
  );
};

As you can guess, it uses $http and $q.resolve which run $digest and all this leads to an infinite loop:

angular.js:63 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"buttonAddFriendVisibled()","newVal":{},"oldVal":{}},{"msg":"buttonRemoveFriendVisibled()","newVal" :{},"oldVal":{}}],[{"msg":"buttonAddFriendVisibled()","newVal":{},"oldVal":"<>"},{"msg":"buttonRemoveFriendVisibled( )","newVal":{},"oldVal":"<>"}],[{"msg":"buttonAddFriendVisibled()","newVal":{},"oldVal":"<>"}, {"msg":"buttonRemoveFriendVisibled()","newVal":{},"

How do I make the button visibility calculation if the visibility depends on the logged in user?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
V
Vladimir, 2017-01-09
@Casufi

Read these two articles in full.
https://github.com/rwwagner90/angular-styleguide-es6
https://www.sitepoint.com/writing-angularjs-apps-u...
1) Too many extra variables in $scope
2) Need to use ControllerAs

L
lega, 2017-01-09
@lega

You can do something like this, but it's better to pull it into the service or just into a separate function.

$scope.buttonAddFriendVisibled = (function(){
var result;
return function() {
  if(result != null) return result;
  result = false;
  var authenticated = $scope.authenticated;
    authenticated.hasFriend(user)
      .then(function(hasFriend) { 
        result = $scope.user.id != authenticated.id && !hasFriend; 
      })
  };
})();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question