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