1

I am trying to understand Interpolation concepts in Angular JS and I have written this code. I am trying to enter a text in input box and based on the template in text area tag it should replace the variable and update the final message dynamically in previewText field. How to achieve this.

<!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>

2 Answers 2

1

Simply remove your $scope.watch and replace it with

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

then add

ng-change="update()"

to both your <input> and <textarea>.

Note that since you've specified <input type="email">, the to model will only be valid and set if the input value is an email address, excluding initial state.

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That worked :) Can you please provide me with any suggestions for material where I can understand Interpolate concepts in Angular better?
@ang123 you seem to understand them quite well. All you were missing was a hook to update previewText when the to model changed
0

Interpolation markup with embedded expressions is used by AngularJS to provide data-binding to text nodes and attribute values.

An example of interpolation is shown below:

Hello {{imagename}}!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.