Answer the question
In order to leave comments, you need to log in
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>
// Определение видимости кнопки Добавить в друзья
$scope.buttonAddFriendVisibled = function() {
return (
$scope.authenticated.hasFriend(user)
.then(function(hasFriend) {
return $scope.user.id != $scope.authenticated.id && !hasFriend;
})
);
};
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":{},"
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question