0

I have following part of code.

var app = angular.module('app', []);

app.controller('DemoCtrl', function($scope, accessService) {
  $scope.isPageAccessible = function(pageCode) {
    return accessService.checkAccess(pageCode);
  }; 
});

app.factory('accessService', function(){
  var availableRoles = ['PROFILE'];
  var service = {};
  service.checkAccess = function (role) {
        console.log('Check role: ' + role);
        return availableRoles.some(function (element) {
            return element == role;
        });
    };
  return service;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul class="nav nav-tabs" ng-app="app" ng-controller="DemoCtrl">
  <li class="active"><a href="#">Home</a></li>
  <li><a ng-show="isPageAccessible('PROFILE')" href="#">Profile</a></li>
  <li><a ng-show="isPageAccessible('MESSAGE')" href="#">Messages</a></li>
</ul>

And I surprised why angular call function isPageAccessible() multiple times. In my mind function isPageAccessible() should be called only twice, but in the concole I see 4 calling. If somebody know why?

cane
  • 892
  • 1
  • 10
  • 16
  • Check this http://stackoverflow.com/questions/20913569/angularjs-ng-show-method-getting-called-way-too-many-times – random Aug 04 '16 at 19:33
  • 1
    [This is a good one too](http://stackoverflow.com/questions/18581170/controller-function-getting-called-twice-using-ng-show) – jktin12 Aug 04 '16 at 19:34
  • If you're displaying links based on user roles, you'll want to use ng-if rather than ng-show. ng-show relies on CSS which can be disabled. ng-if removes it from the DOM. – Rob Aug 04 '16 at 19:36

1 Answers1

0

it's happens because of two-way data binding in angular. to solve such problem I did following: use one-way data binding.

var app = angular.module('app', []);

app.controller('DemoCtrl', function($scope, accessService) {
  $scope.isProfile = accessService.checkAccess('PROFILE');
  $scope.isMessage= accessService.checkAccess('MESSAGE');
});

app.factory('accessService', function(){
  var availableRoles = ['PROFILE'];
  var service = {};
  service.checkAccess = function (role) {
        console.log('Check role: ' + role);
        return availableRoles.some(function (element) {
            return element == role;
        });
    };
  return service;
});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<ul class="nav nav-tabs" ng-app="app" ng-controller="DemoCtrl">
  <li class="active"><a href="#">Home</a></li>
  <li ng-if="::isProfile"><a href="#">Profile</a></li>
  <li ng-if="::isMessage"><a href="#">Messages</a></li>
</ul>

From version 1.3 I can use one-way data binding. Here is only tiny thing for me - it's not working with functions and I have to move roles into controller.

cane
  • 892
  • 1
  • 10
  • 16