2

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

1 Answer 1

2

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];
         });

Working fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Wow amazing. Thanks. I figured I'd have to do something fancy with "watch" but I'm still pretty new to this. Thank you so much for showing me this!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.