ng-show 条件(以字符串形式存储在变量中)未评估 angular js

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

我想根据一个表达式显示一个 div 但该表达式以字符串形式存储在一个变量中,是否可以为 ng-show / [=13 计算一个表达式变量=]. 喜欢:

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

尝试

控制器

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

VIEW

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

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

提示

尝试使用 ng-if 而不是 ng-show / ng-hideng-if 不监视此指令中绑定变量的变化,可以提高性能。

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

虽然其他 post 已经回答了,只是想补充.. 因为在你的问题中你说.. the expression is stored in a variable in string form, is it possible to do evaluate an expression variable ..

简单的答案是不,你不能计算 angularjs 表达式字符串变量,但你只能计算有效的表达式。(通过 JS 或通过 angular 变量)

看下面这段代码,区分一下

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>

: