Skip to content Skip to sidebar Skip to footer

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-layo

Solution 1:

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() {
    returnlocalStorage.getItem('grid-layout') == 'list';
}

//In template
<div ng-if="checkLocalStorage()"></div>

Solution 2:

I don't think you can use localstorage inside the ng-if since ng-if is angular directive it only supports angular expression. one thing you can do is create a scope function and return the localstorage value

ng-if="getStorage() == 'list'"

$scope.getStorage = function(){
 returnlocalStorage.getItem('grid-layout');
}

Solution 3:

Move your logic to the controller:

In HTML call method :

ng-if="checkForLocalStorage()"

and in controller, inject $window and write method like :

$scope.checkForLocalStorage = function(){
   return$window.localStorage.getItem('grid-layout') == 'list' 
}

Further, the better approach is to make boolean property in controller, and bind it to the ng-if. else your method will be called on every model\binding change because of angular digest cycle.

You can do do it like, In controller:

$scope.isGridLayoutList= $window.localStorage.getItem('grid-layout') == 'list' ;

and in HTML : ng-if="isGridLayoutList"

Solution 4:

There is no need to store a function in $scope variable and call it in html. You can store the truthy/falsy value directly in a variable and use it in ng-if, Better and reduces lines of code

$scope.toShow = (localStorage.getItem('grid-layout') == 'list');

<divng-if="toShow"></div>

Post a Comment for "How To Use Javascript Inside Ng-if Angularjs?"