基于一个输入字段填充另一个输入字段

Populate one input field based on other

本文关键字:字段 输入 另一个 填充 于一个      更新时间:2023-09-26

我在项目中使用angular.js。在模板中,我有:

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

我现在controller只使用一种模型$scope.f1

我想根据Field 1预填充Field 2。但是由于我使用相同的模型如果我用Field 2写一些东西会覆盖Field 1.

我不希望这种行为。我应该能够在不影响Field 1的情况下稍后编辑Field 2.

有没有办法实现这种行为?

您可以使用

$watch,它注册一个侦听器回调,以便在watchExpression更改时执行。

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

工作演示