2014-05-16 49 views
7

有沒有辦法讓AngularJS在模型數據中評估一個表達式?AngularJS Expression in Expression

HTML:

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


型號:

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

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

最終的結果將是:This is some text and this is the rest of it

回答

10

可以使用$interpolate服務插值串...

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

這就是答案!非常感謝! – AnotherDeveloper

+0

非常好!謝謝 –

1

當你在使用JavaScript的模型,你可以做一些簡單的像這樣:

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

並在視圖,讓您的<p>{{txt}}</p>

或者可以串表達式一起<p>{{txt}} {{rest}}</p>

5

你可以在括號內執行JS:

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

或者創建一個返回你想要的文字功能:

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

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

OP詢問表達式本身是否可以成爲'model'的一部分(不僅僅是bindi NG)。 –

+2

@ PM77-1和我向他展示瞭如何使用函數。 – SomeKittens

+1

請看他如何定義'txt'。你的代碼會產生所需的結果嗎? –