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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With