我刚刚开始使用Angular JS将我的模型绑定到许多输入字段。我的型号包括一个电话号码,格式为单个字符串:“1234567890”。
function Ctrl($scope) {
$scope.phone = "1234567890";
}
我想有三个输入字段绑定到电话号码的相关部分(区号,三位数,四位数)。
<div ng-controller="Ctrl">
(<input type="text" maxlength="3">) <input type="text" maxlength="3"> - <input type="text" maxlength="4">
</div>
但是,我无法为每个输入字段创建一个双向绑定到电话字符串的部分。我已经尝试了两种不同的方法:
方法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>
方法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>
使用方法1,但添加$ watch:
$scope.$watch(
function() {return $scope.phone1 + $scope.phone2 + $scope.phone3; }
,function(value) { $scope.phone = value; }
);
我更喜欢@ Karl的版本:
$scope.$watch('phone1 + phone2 + phone3',
function(value) { $scope.phone = value; }
);