如何在Angular中为一个模型使用字符串的一部分?

问题描述 投票:4回答:1

我刚刚开始使用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>
javascript angularjs
1个回答
7
投票

使用方法1,但添加$ watch:

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

fiddle

我更喜欢@ Karl的版本:

$scope.$watch('phone1 + phone2 + phone3',
   function(value) { $scope.phone = value; }
);
© www.soinside.com 2019 - 2024. All rights reserved.