HJain
HJain

Reputation: 85

ng-show condition (stored in a string form in variable ) is not evaluating angular js

I want to show a div according to a expression but the expression is stored in a variable in string form, is it possible to do evaluate an expression variable for ng-show / ng-hide. like:

$scope.condition = {"SHOW":'(model1  === 'test1')'}
<div ng-show="condition['SHOW]"></div> something like this.

Upvotes: 1

Views: 2159

Answers (2)

anoop
anoop

Reputation: 3822

Though it's already answered by other post, Just wanted to add.. Since In your question you said.. the expression is stored in a variable in string form, is it possible to do evaluate an expression variable ..

The simple answer is NO you can't evaluate angularjs expression string variable , but you can only evaluate the valid expression.(either by JS or by angular variable)

See this below code, to differentiate

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

//myApp.directive('myDirective', function() {});
myApp.controller('MyCtrl', function MyCtrl($scope) {
  $scope.condition = {
    SHOW1: "'test'  == 'NOTEST'",
    SHOW2: 'test' == 'test'
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-show="condition.SHOW1">
    1.Not working, as it is simple string("'test' == 'NOTEST'").
  </div>

  <div ng-show="condition.SHOW2">
    2.Working, valid boolean Angular variable
  </div>

  <div ng-show="'test'=='test'">
    3.Working, valid boolean simple JS expression
  </div>
</div>

:

Upvotes: 1

daan.desmedt
daan.desmedt

Reputation: 3820

Try

CONTROLLER

$scope.test = 'test1';
$scope.condition = { show : ($scope.test  === 'test1')};

VIEW

<div ng-show="condition.show">something like this.</div> 

which is the same as

<div ng-show="condition['show']">something like this.</div> 

TIP

Instead of using ng-show / ng-hide, try to use ng-if. ng-if doesn't watch for changes on the binded variables inside this directive and can improve performance.

<div ng-if="condition['show']">something like this.</div> 

Upvotes: 2

Related Questions