AngularJS Expression in Expression

独自空忆成欢 提交于 2019-12-18 16:51:39

问题


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>



来源:https://stackoverflow.com/questions/23706006/angularjs-expression-in-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!