ang123
ang123

Reputation: 33

Interpolation in Angular JS

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>

Upvotes: 1

Views: 1682

Answers (2)

Skalyan
Skalyan

Reputation: 1

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

Upvotes: 0

Phil
Phil

Reputation: 164764

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

Upvotes: 1

Related Questions