AngularJS Expression in Expression

2019-02-09 14:10发布

问题:

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.

回答1:

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



回答2:

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>


回答3:

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>