I need to automatically populate second textbox once the first textbox is populated by user using angularjs. Both of them have their own ng-model so I can not change ng-model. Is there a way I can just copy the value from first textbox to second by keeping ng-model different?
2 Answers
In the controller, you need to build the logic to assign model1 value to model2 whenever there is a change in model1
Your html part :
<input ng-model='model1" ng-change="update2()">
<input ng-model='model2" >
And somewhere in the relevant controller,
$scope.update2 = function(){
$scope.model2 = $scope.model1;
}
6 Comments
ad8228
Thank you for your response, but after I populate the second textbox, user should again be able to change the value in second textbox. And that updated value should be saved.
arkoak
This method allows 2nd value to be changed and saved in model2, however it does not update the first value back as I have not added a 'ng-change' directive to the 2nd input.
Ramesh Rajendran
Your code given a error. the model1 and model2 is undefined :( . please use ` $scope.model1`
ad8228
Below answer using $watch does copies the value from first textbox to second, but it only saves the first value even when i modify the value of second text box. Is there a way to copy the value and also be able to modify it?
arkoak
you can use the ng-submit tag and specify the function
<form ng-submit="process()"> , this function can send the model values instead of the html values |
You can monitor changes to your $scope using the $watch function. This is a more appropriate way for binding changes in Angular. try below snippet:
Controller:
$scope.$watch('first',function(){
$scope.second = $scope.first;
});
HTML:
<input ng-model='first'>
<input ng-model='second' >
1 Comment
ad8228
Thank You for your answer. It does copy the value of first textbox into second one, but when i modify the value of second textbox and save it. only the first value gets save in both textbox. I want user to be able to modify the value and save the changes.