1

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.
Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
HJain
  • 85
  • 8

2 Answers2

2

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> 
daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
  • 1
    Or in the view - `ng-show="condition['SHOW].model1 === 'test1'"` – Alon Eitan Jun 12 '17 at 11:40
  • @AlonEitan - exactly - but i'm PERSONALLY not a real big fan of additional 'logics' on view level. I try to keep logics on controller side - to keep clarity. It's personal I guess. :) – daan.desmedt Jun 12 '17 at 11:42
  • @daan.desmedt: your solution is good, but I guess qstn was bit different, as it says : *...but the expression is stored in a variable in string form..,*, :), It's like `show : "($scope.test === 'test1')"` – anoop Jun 12 '17 at 11:47
1

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>

:

anoop
  • 3,812
  • 2
  • 16
  • 28