AngularJS: two inputs with a separate ngModel, one update of another value

I am trying to have two separate input fields, each with its own model, with one of them updating the other value by default.

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

As a result, if you enter your email address, the username will be automatically filled in by him, although the username can be changed if you enter it into it.

This does not work. Instead, ng-model="username" overrides the attr value, regardless of what is set there. Thus, the username entry remains blank until it explicitly enters it.

Is there a way to do this along these lines, or does he need a special directive or something else?

+4
source share
1 answer

Do not use value :

 <input type="text" name="username" placeholder="Username" ng-model="username"> 

Use $watch in the controller:

 function MyCtrl($scope) { $scope.$watch('email', function(value) { $scope.username = value }); } 

fiddle

+6
source

Source: https://habr.com/ru/post/1479449/


All Articles