Keith Keith - 4 months ago 9
AngularJS Question

Evaluating Angular expressions in Javascript strings

This is probably an easy question, but hard to search for...

I have the text on a button changing based on some condition:

<button>{{buttonText()}}</button>
<script>
$scope.buttonText = function() {
if (condition) {
return "Here is {{otherVar}}";
} else {
return "Nope!";
}
}
</script>


Of course the button shows "Here is {{otherVar}}" without parsing
otherVar
into the expression. Is there some way to have angular evaluate the js string?

The entire string gets passed from a CMS so I can't just do
return "Here is" + otherVar;
I'm looking for something like
return angularEval("Here is {{otherVar}}");

Answer
<button>{{buttonText()}}</button>
<script>
  //controller injects $interpolate like app.controller($scope, $interpolate)
    $scope.buttonText = function() {
        if (condition) {
            var dataObj = { otherVar : 'bla' }; //can be scope
            var exp = $interpolate('Here is {{otherVar}}');
            return exp(dataObj);
        } else {
            return "Nope!";
        }
    }
</script>

read more:https://docs.angularjs.org/api/ng/service/$interpolate

also simpler solution is to put condition and otherVar in the scope and

<button>{{ condition ? 'Here is ' + otherVar : 'Nope!'}}</button>
Comments