Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JavaScript inside ng-if AngularJS?

I was trying to use a JavaScript expression with ng-if. However, it didn't do anything. It allways returns false.

What i tried was following:

ng-if="localStorage.getItem('grid-layout') == 'list' (if true, show div)

The div doens't render, because it allways returns false. The grid-layout value is saved in the localStorage. This is not the issue.

I checked the documentation on the website. Angular says the following about ng-if

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

If the expression is falsy then the element is removed from the DOM tree. If it is truthy a copy of the compiled element is added to the DOM tree.

Is it possible to use just JavaScript inside ng-if? If not, how can i archieve what i was trying to do?

like image 287
Red Avatar asked Sep 05 '25 22:09

Red


1 Answers

You can use Javascript expression inside an ng-if, but you are only able to access properties that are in the $scope of the current template.

It's unlikely that localStorage would be available to you unless you had specifically added it to the $scope object.

One approach would be to write a function attached to the $scope in your controller:

//in controller JS
$scope.checkLocalStorage = function() {
    return localStorage.getItem('grid-layout') == 'list';
}

//In template
<div ng-if="checkLocalStorage()"></div>
like image 181
iamalismith Avatar answered Sep 10 '25 10:09

iamalismith