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.

2 Answers 2

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> 
Sign up to request clarification or add additional context in comments.

3 Comments

Or in the view - ng-show="condition['SHOW].model1 === 'test1'"
@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: 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')"
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>

:

1 Comment

Upvoted your answer for you clarification around the string expression. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.