angularjsexpressionng-showevaluateng-hide

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.

Solution

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

    :