How to use part of a string for one model in Angular?

I'm just starting to use Angular JS to bind my model to a series of input fields. My model contains a phone number formatted as one line: "1234567890".

function Ctrl($scope) { $scope.phone = "1234567890"; } 

I would like to have three input fields that are associated with the corresponding parts of the phone number (city code, three-digit number, four-digit number).

 <div ng-controller="Ctrl"> (<input type="text" maxlength="3">) <input type="text" maxlength="3"> - <input type="text" maxlength="4"> </div> 

However, I am having problems creating a two-way binding for each input field to parts of the telephone line. I already tried two different approaches:

Approach 1

 ---- JavaScript ---- function Ctrl($scope) { $scope.phone = "1234567890"; $scope.phone1 = $scope.phone.substr(0,3); $scope.phone2 = $scope.phone.substr(2,3); $scope.phone3 = $scope.phone.substr(5,4); } ---- HTML ---- <div ng-controller="Ctrl"> (<input type="text" maxlength="3" ng-model="phone1">) <input type="text" maxlength="3" ng-model="phone2"> - <input type="text" maxlength="4" ng-model="phone3"> </div> 

Approach 2

 ---- JavaScript ---- function Ctrl($scope) { $scope.phone = "1234567890"; } ---- HTML ---- <div ng-controller="Ctrl"> (<input type="text" maxlength="3" ng-model="phone.substr(0,3)">) <input type="text" maxlength="3" ng-model="phone.substr(2,3)"> - <input type="text" maxlength="4" ng-model="phone.substr(5,4)"> </div> 
+4
source share
1 answer

Use approach 1, but add $ watch:

 $scope.$watch( function() {return $scope.phone1 + $scope.phone2 + $scope.phone3; } ,function(value) { $scope.phone = value; } ); 

fiddle

I like @Karl's better version:

 $scope.$watch('phone1 + phone2 + phone3', function(value) { $scope.phone = value; } ); 
+7
source

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


All Articles