Reputation: 329
Angularjs newbie here.. I have two input boxes,
<input type="text" class="form-control" ng-model="d.d_oad1">
<input type="text" class="form-control" ng-model="d.c_oad1">
then I have
<input type="text" class="form-control" ng-model="d.d_oad2">
<input type="text" class="form-control" ng-model="d.c_oad2">
<input type="text" class="form-control" ng-model="d.d_oad3">
<input type="text" class="form-control" ng-model="d.c_oad3">
and so on...
I need to populate value from the first input box to the next, while keeping the second input box's update independent. For example, I need to populate data from input box with ng-model d.d_oad1 to d.c_oad1, similarly, d.d_oad2 to d.c_oad2 and so on.. It would have been easy if I could use the same ng-model for both, however that is not possible...
Upvotes: 1
Views: 1009
Reputation: 56487
So to begin, whatever gets changed in input1 will be stored in variable1(d.d_oad1
) and whatever is changed in input2 will get stored in variable2(d.c_oad2
), to create the below functionality needed.
First we define an ng-change
which runs whenever the ng-modal
value changes (i.e. d.d_oad1) and call a function call copy()
and pass the value of variable 1(d.d_oad1
) to the function.
<input type="text" class="form-control" ng-model="d.d_oad1" ng-change="copy(d.d_oad1)">
So inside this copy function we can write the functionality needed.
Copy functionality:
$scope.copy = function(val) {
$scope.d.c_oad2 = angular.copy(val);
}
Snippet:
Here the copy function will receive the value of variable1 in the first arguement and assign it to the second arguement.
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.d = {
d_oad1: "",
c_oad1: "",
d_oad2: "",
c_oad2: "",
d_oad3: "",
c_oad3: ""
}
$scope.copy = function(str, val) {
var key = "c_"+str.split("_")[1];
$scope.d[key] = val;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
<input type="text" class="form-control" ng-model="d.d_oad1" ng-change="copy('d.d_oad1', d.d_oad1)"><br>
<input type="text" class="form-control" ng-model="d.c_oad1"><br>
<input type="text" class="form-control" ng-model="d.d_oad2" ng-change="copy('d.d_oad2', d.d_oad2)"><br>
<input type="text" class="form-control" ng-model="d.c_oad2"><br>
<input type="text" class="form-control" ng-model="d.d_oad3" ng-change="copy('d.d_oad3', d.d_oad3)"><br>
<input type="text" class="form-control" ng-model="d.c_oad3">
</div>
Upvotes: 1