我正在尝试理解 Angular JS 中的插值概念,并且我已经编写了这段代码。我正在尝试在输入框中输入文本,并根据文本区域标签中的模板,它应该替换变量并在 previewText 字段中动态更新最终消息。如何实现这一点。
<!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>