我想根据表达式显示div,但表达式以字符串形式存储在变量中,是否可以执行评估表达式变量为ng-show
/ng-hide
。 喜欢:ng显示条件(存储在变量中的字符串形式)不是评估角度js
$scope.condition = {"SHOW":'(model1 === 'test1')'}
<div ng-show="condition['SHOW]"></div> something like this.
我想根据表达式显示div,但表达式以字符串形式存储在变量中,是否可以执行评估表达式变量为ng-show
/ng-hide
。 喜欢:ng显示条件(存储在变量中的字符串形式)不是评估角度js
$scope.condition = {"SHOW":'(model1 === 'test1')'}
<div ng-show="condition['SHOW]"></div> something like this.
虽然它已经被其他后回答,只是想补充.. 因为你的问题,你说... 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>
:
尝试
CONTROLLER
$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>
TIP
而不是使用ng-show
/ng-hide
的,尽量使用ng-if
。 ng-if
不会监视此指令中绑定变量的更改并可以提高性能。
<div ng-if="condition['show']">something like this.</div>
或者在视图 - '纳克放映= “条件['SHOW] .model1 === 'TEST1'”' –
@AlonEitan - 恰好 - 但我从个人角度来看,他并不是一个真正的追求'逻辑'的大粉丝。我试图保持控制器端的逻辑 - 保持清晰。我想是个人的。 :) –
好吧,你有我的upvote;) –
Upvoted你的答案为你澄清字符串表达式。谢谢 :) –