1

我想了解Angular JS中的插值概念,並且我已經編寫了這段代碼。我試圖在輸入框中輸入文本,並基於文本區域標籤中的模板,它應該替換變量並在previewText字段中動態更新最終消息。如何實現這一點。Angular JS插值

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> 
<meta charset=utf-8 /> 
<title>JS Bin</title> 
</head> 
<body ng-app="myApp"> 
<div ng-controller="MyController"> 
<input ng-model="to" 
     type="email" 
     placeholder="Recipient" /> 
<textarea ng-model="emailBody"></textarea> 
<pre>{{ previewText }}</pre> 
</div> 
</body> 
<script> 
angular.module('myApp', []).controller('MyController',function($scope, $interpolate) { 
    $scope.to = 'text'; //static value.Trying to make this dynamic. How  to achieve it?? 
//  $scope.$watch('to',function(newValue,oldValue,scope) 
    //{ 
    //$scope.to = $interpolate($scope.to)($scope); 
    //}); 
    $scope.emailBody = 'Hello {{ to }},My name is Ari too!'; 
    // Set up a watch 
    $scope.$watch('emailBody', function(body) { 
    if (body) { 
     var template = $interpolate(body); 
     $scope.previewText = 
     template({to: $scope.to}); 
    } 
    }); 
    }); 



</script> 
</html> 

回答

1

只需刪除您$scope.watch

$scope.update = function() { 
    $scope.previewText = $interpolate($scope.emailBody)($scope); 
}; 
$scope.update(); 

取代它再加入

ng-change="update()" 

<input><textarea都>。

請注意,由於您已指定<input type="email">,因此to型號僅在輸入值爲電子郵件地址(不包括初始狀態)時纔有效並設置。

http://plnkr.co/edit/AOR6a7TAYhoXYSnJh2r4?p=preview

+0

謝謝。這工作:)你可以請我提供任何建議,我可以理解的材料在Angular中插入概念更好嗎? – ang123

+0

@ ang123你似乎很瞭解他們。你所缺少的只是當'to'模型改變時更新'previewText'的鉤子 – Phil