ng-show条件(以变量中的字符串形式存储)不评估角度js

时间:2017-06-12 11:31:48

标签: angularjs expression ng-show evaluate ng-hide

我想根据表达式显示div但是表达式以字符串形式存储在变量中,是否可以为endlocal / ng-show计算表达式变量。 喜欢:

ng-hide

2 个答案:

答案 0 :(得分:2)

尝试

<强> CONTROLLER

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

查看

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

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

提示

尝试使用ng-show,而不是使用ng-hide / ng-ifng-if并未注意此指令中绑定变量的更改,可以提高性能。

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

答案 1 :(得分:1)

虽然它已经被其他帖子回答,但只是想添加.. 因为在你的问题中,你说.. the expression is stored in a variable in string form, is it possible to do evaluate an expression variable ..

简单的答案是NO,你不能评估angularjs表达式字符串变量,但你只能评估有效的表达式。(通过JS或角度变量)

请参阅以下代码,以区分

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>