2014-05-16 15 views
7

Czy istnieje sposób, aby AngularJS oceniał wyrażenie w danych modelu?Wyrażenie AngularJS w wyrażeniu

HTML:

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


Model:

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

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

Efektem końcowym będzie: This is some text and this is the rest of it.

Odpowiedz

10

Można korzystać z usługi $interpolate interpolować ciąg ...

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

To jest odpowiedź! Wielkie dzięki! – AnotherDeveloper

+0

Bardzo ładne! Dzięki –

1

Jak używasz JavaScript dla modelu można zrobić coś prostego, jak to:

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

A w widoku, trzymaj <p>{{txt}}</p>

Alternatywnie można String wyrażenia razem <p>{{txt}} {{rest}}</p>

5

Możesz wykonać JS w nawiasach:

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

Albo utworzyć funkcję, która zwraca tekst chcesz:

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

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

OP zapytał, czy samo wyrażenie może być częścią 'modelu' (nie tylko bindi ng). –

+2

@ PM77-1 i pokazałem mu, jak z funkcją. – SomeKittens

+1

Zobacz, jak definiuje 'Txt'. Czy twój kod da pożądany rezultat? –

Powiązane problemy