Reputation: 85
Hi I have a weird scenario for two way binding that I just can't sort out. I have 3 different text input fields and a 4th that is somewhat of a concatenation of the other three. For example:
Text1: A
Text2: B
Text3: C
Text4: A/B/C
What I would really like is for Text4
to auto update as either Text 1,2 or 3
are updated but also vice-versa!
Any ideas? I'm totally stumped on this...
Cheers, Jon
Upvotes: 2
Views: 93
Reputation: 24676
As long as you have a separator (as it appears you're using '/') it's pretty straightforward.
First our html:
Text 1: <input ng-model="text1">
Text 2: <input ng-model="text2">
Text 3: <input ng-model="text3">
Text 4: <input ng-model="text4">
Then we'll do 2 watches, one for each direction:
From 1,2,3 to 4. This concatenates 1,2,3 with our separator and watches that value. If the concatenated result changes then we update 4 with the result.
$scope.$watch (
function () {
return $scope.text1+'/'+$scope.text2+'/'+$scope.text3;
},function(newval) {
$scope.text4 = newval;
});
From 4 to 1,2,3 we put our watch on 4 and when it changes split out 1,2 and 3 using the separator:
$scope.$watch ('text4',
function(newval) {
texts = newval.split("/");
$scope.text1 = texts[0];
$scope.text2 = texts[1];
$scope.text3 = texts[2];
});
Upvotes: 2