AngularJS Expression in Expression

前端 未结 3 767
长情又很酷
长情又很酷 2021-01-02 17:37

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

HTML:

{{Txt}}


Model:

相关标签:
3条回答
  • 2021-01-02 17:58

    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>
    
    0 讨论(0)
  • 2021-01-02 18:04

    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>

    0 讨论(0)
  • 2021-01-02 18: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

    0 讨论(0)
提交回复
热议问题