Sync two textboxes with different models

狂风中的少年 提交于 2019-12-08 08:56:10

问题


I have a simple angular app with two textboxes with different models

First Email: <input ng-model="firstEmail"/>
Second Email: <input ng-model="secondEmail"/>

Now, if something is typed in first email, I want it to get populated in second email but if second email is manually edited, then this binding should stop i.e. further changes in first email should't affect second email.

My code:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.1/angular.min.js"></script>
<script>
var emailApp = angular.module('emailApp', []);
emailApp.controller('EmailCtrl', ['$scope', function ($scope) {

}]);
</script>
</head>
<body ng-app="emailApp">
  <div ng-controller="EmailCtrl">
      First Email: <input ng-model="firstEmail"/>
      <br>
      Second Email: <input ng-model="secondEmail"/>
      </select>
  </div>
</body>
</html>

回答1:


You need to use watch to bind the content in secondEmail from the firstEmail.

  $scope.$watch('firstEmail',function(newVal,oldVal){
    $scope.secondEmail=newVal;
    })

Plunker




回答2:


Use ng-change directive to update the value.

<body ng-app="emailApp">
  <div ng-controller="EmailCtrl">
      First Email: <input ng-model="firstEmail" ng-change="secondEmail=firstEmail"/>
      <br>
      Second Email: <input ng-model="secondEmail"/>
  </div>
</body>

Working Plunkr

This could help you. Thanks.



来源:https://stackoverflow.com/questions/28497407/sync-two-textboxes-with-different-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!