ng-show binding to string expression in angular

Luiz Henrique Martins Lins Rol picture Luiz Henrique Martins Lins Rol · Nov 27, 2013 · Viewed 10.6k times · Source

Is there a way to bind a ng-show expression to a string which contains the bind expression itself?

For Instance:

field={};
field.a=true;
field.showExpression='a == true';

<input ng-show="field.showExpression">

I´ve tried <input ng-show="{{field.showExpression}}"> as well, but none of them seems to work.

I want the bind to stay active, so that when the field.a object changes from true to false the expression gets evaluated again, hiding the input.

Just as background, i´m trying to implement dependant dropdowns, so my showExpressions should be of form field.showExpression='maindropdownValue!=null', and whenever the maindropdown which will be bound to the maindropdownValue gets selected the second one gets displayed.

I´m using angular 1.0.8

Answer

Daniele Vrut picture Daniele Vrut · Nov 27, 2013

showExpression is evalued as a String not as a JS code. You have to use a function instead.

$scope.isTrue = function() {
    return $scope.field.a; // or a more complex check
}
//
ng-show="isTrue()"

if you only have to check for a boolean, you can check var directly in the view:

ng-show="field.a"

If you really want to use eval, this is what you want:

ng-show="$parent.$eval(field.showExpression)"

link: http://docs.angularjs.org/guide/expression