AngularJS expression in expression

Is there a way to get AngularJS to evaluate an expression in model data?

HTML:

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


Model:

  { Txt: "This is some text {{Rest}}" } { Rest: "and this is the rest of it." } 

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

+7
javascript angularjs angularjs-scope
source share
3 answers

You can use the $interpolate service to interpolate a 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

+10
source share

You can execute JS in brackets:

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

Or create a function that returns the desired text:

 $scope.getText = function() { return $scope.Txt + ' ' + $scope.Rest; } <p>{{getText()}}</p> 
+5
source share

Since you are using javascript for the model, you can do something simple:

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

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

Alternatively, you can combine the expressions <p>{{txt}} {{rest}}</p>

+1
source share

All Articles