我想根据表达式显示一个div,但表达式以字符串形式存储在变量中,是否可以为ng-show
/ng-hide
计算表达式变量。 喜欢:
$scope.condition = {"SHOW":'(model1 === 'test1')'}
<div ng-show="condition['SHOW]"></div> something like this.
试试
控制器
$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-if
。ng-if
不会监视此指令中绑定变量的更改,并且可以提高性能。
<div ng-if="condition['show']">something like this.</div>
虽然其他帖子已经回答了,只是想补充一下。 既然在你的问题中你说..the expression is stored in a variable in string form, is it possible to do evaluate an expression variable ..
简单的答案是否定的,你不能计算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>
: