我试图有两个单独的输入字段,每个字段都有自己的模型,其中一个默认更新另一个的值。
<form id="registerForm" ng-submit="create(email, username, password)">
<input type="text" name="email" placeholder="Email" ng-model="email">
<input type="text" name="username" value="{{email}}" placeholder="Username" ng-model="username">
<input type="password" name="password" placeholder="Password" ng-model="password">
<input type="submit" value="register" class="button" ng-show="!loading">
<input type="submit" value="processing" class="button" disabled ng-show="loading">
</form>
结果是,如果您输入电子邮件,用户名输入将自动填充,但如果专门输入用户名,则可以更改用户名。
但这不起作用。相反,
ng-model="username"
无论那里设置了什么,都会覆盖值 attr。所以用户名输入保持为空,直到明确输入。有没有办法沿着这些路线做到这一点,或者它是否需要特殊指令或其他东西?
最佳答案
不要使用 value
:
<input type="text" name="username" placeholder="Username" ng-model="username">
使用
$watch
在您的 Controller 中:function MyCtrl($scope) {
$scope.$watch('email', function(value) {
$scope.username = value
});
}
fiddle
关于AngularJS:两个具有单独 ngModel 的输入,一个更新另一个的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16408726/