7

Is there a way to have AngularJS evaluate an expression within model data?

HTML:

<p>
{{Txt}}
</p>


Model:

    { 
     Txt: "This is some text {{Rest}}"
    }

    {
      Rest: "and this is the rest of it."
    }

The end result would be: This is some text and this is the rest of it.

3 Answers 3

10

You can use the $interpolate service to interpolate the string...

function ctrl ($scope, $interpolate) {
    $scope.Txt = "This is some text {{Rest}}";
    $scope.Rest = "and this is the rest of it.";
    $scope.interpolate = function (value) {
        return $interpolate(value)($scope);
    };
}

<div ng-app ng-controller="ctrl">
    <input ng-model="Txt" size="60" />
    <p>{{ Txt }}</p>
    <p>{{ interpolate(Txt) }}</p>
</div>

JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

5

You can execute JS within the brackets:

<p>{{Txt + ' ' + Rest}}</p>

Or create a function that returns the text you want:

$scope.getText = function() {
  return $scope.Txt + ' ' + $scope.Rest;
}

<p>{{getText()}}</p>

5 Comments

OP asked whether the expression itself could be a part of model (not just binding).
Please see how he defines Txt. Will your code produce the desired result?
Our goal was to allow the user to enter text with a handlebar expression inside their text.
@Jason In the future, to save everyone's time, please read up on the XY problem: meta.stackoverflow.com/questions/66377/what-is-the-xy-problem I'll see what I can do about getting the user to enter {{}}
@SomeKitten I am presenting a solution that doesn't exist to explain the problem I am trying to solve. This functionality is possible in handlebars already, but there is not a way to do this in Angular unfortunately.
1

As you are using javascript for the model you can do something simple like this:

var rest = 'and this is the rest of it';
$scope.txt = 'This is some text ' + rest;

And in the view, keep your <p>{{txt}}</p>

Alternatively you can string the expressions together <p>{{txt}} {{rest}}</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.