Thịnh Phạm Thịnh Phạm - 1 year ago 56
AngularJS Question

Convert an express-like string to an expression in Angular view

Assuming that I have an expression-like string in my scope

$scope.expressionString = 'model.key == "anything"'

I want to use this string as an expression in view, can I do that?

In view, I will have something like

<div ng-if="expressionString"></div>
but of course, expressionString should be something else instead.

I appreciate any help. Cheers!

Answer Source

You can use $eval to evaluate your expression , there are two ways to do it in your case

Solution 1

 <div ng-if="$eval(expressionString)"></div>

Solution 2

In the controller store the evaluated value of the expression like below

  $scope.expressionString = $scope.$eval('model.key == "anything"')

and then in the view simply use it without using $eval in the view

 <div ng-if="expressionString"></div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download