Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-show doesn't work properly when value changes

I'm trying to show div depends on permission of log in user.

<div class="container">
    <p> {{permission}}</p>
    <div ng-show="permission" class="admin_panel">
      ....
    </div>
</div>

and in controller, it is set:

$scope.init = function(){

    if($window.sessionStorage.isAdmin){
      $scope.permission = $window.sessionStorage.isAdmin;
    }
    $log.info("are you admin??? " + $scope.permission);
};
$scope.init();

In console, I could verify that permission was set to false and {{permission}} also showed its value is false. However, ng-show is still showing even though the value is false. I'm not sure what's wrong with this.

like image 704
REALFREE Avatar asked Dec 06 '14 21:12

REALFREE


2 Answers

I had a similar problem except that my variable was changed inside a timeout function like this:

<div ng-show="check"> something .... </div>    

setTimeout(function(){
   check = false;
   },500);

the problem was solved when i added $scope.$apply() inside timeout:

setTimeout(function(){
   check = false;
   $scope.$apply()
   },500);
like image 161
mohammad eslahi sani Avatar answered Oct 05 '22 08:10

mohammad eslahi sani


If you want to show or hide some content that depends of the user permissions, instead of using "ng-show", you should use "ng-if".

ng-show/ng-hide only adds or remove a CSS class that show or hide that element (display:none), but an user could change it easily in the browser.

Using ng-if: "If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM."

https://docs.angularjs.org/api/ng/directive/ngIf

like image 27
Fabricio Duarte Avatar answered Oct 05 '22 10:10

Fabricio Duarte