Deepankar Bajpeyi
Deepankar Bajpeyi

Reputation: 5859

Populate one input field based on other

I am using angular.js in my project. In the template I have :

 <div class='form-group'>
   <label>Field 1</label>
  <input type='text' ng-model='f1' required class="form-control">
 </div>


 <div class='form-group'>
    <label>Field 2</label>
     <input type='text' ng-model='f1' required class="form-control">
 </div>

My controller right now is using only one model $scope.f1

I want to pre-populate Field 2 based on Field 1. But since I am using the same model if I write something in Field 2 overwrites Field 1.

I don't want this behavior. I should be able to edit Field 2 later without affecting Field 1.

Is there a way to achieve this behavior ?

Upvotes: 1

Views: 1764

Answers (1)

Satpal
Satpal

Reputation: 133403

You can use $watch, it registers a listener callback to be executed whenever the watchExpression changes.

$scope.$watch(function () {
    return $scope.f1;
},
function (newValue, oldValue) {
    $scope.f2 = $scope.f1;
}, true);

Working Demo

Upvotes: 5

Related Questions