角度 - 将两个输入ng模型合并为一个

时间:2015-10-14 18:57:11

标签: javascript angularjs

我是Angular的新手,请帮助我。我有两个输入字段,一个带区号,另一个带数字。

// First input field for area code
<input area-input type="tel" required="true" name="area" 
ng-model="employee.home.area"></input>

// Second input field for number
<input phone-input type="tel" required="true"
name="number" ng-model="employee.home.number"></input>

我想将它们组合成区号+数字。

提前致谢。任何建议或帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以在html on

中使用{{employee.home.area}}+{{employee.home.number}}
use `employee.home.area+employee.home.number` in your `controller`

希望这有帮助

答案 1 :(得分:0)

您可以编写自定义指令,并使用parsers中的formattersngModelControllers

所以你可以得到这样的东西:

angular.module('app', []).
controller('ctrl', function($scope,$timeout) {
  $scope.employee = {home : {area:'area', number:'number'}};
  })
  .directive('phone', function() {
    function formatPhone(value) {
      console.log('format',value);
          if (!value) return;
          if (!value.number) return value.area;
          value.area = value.area||'';
          return value.area + "-" + value.number;
        }
    return {
      require: 'ngModel',
      scope:{
        ngModel:'='
      },
      link: function(scope, element, attrs, ngModel) {
        scope.$watch(function(){return scope.ngModel;},function(n){
          if(!n) scope.ngModel={area:"",number:""}
          console.log('watch',n);
          ngModel.$viewValue= formatPhone(n);
          ngModel.$render();
        },true);
        
        ngModel.$formatters.push(formatPhone);
        ngModel.$parsers.push(function(value) {
          console.log(value, value.split('-'));
          var parts = value.split('-');
          return {
            area: parts[0],
            number: parts[1]||''
          };
        });
      }
    };
  })
<script data-require="angular.js@1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <h1>Hello Plunker!</h1>
    // First input field for area code<br/>
    <input area-input="" type="tel" required="true" name="area" ng-model="employee.home.area" /> 
    <br/>// Second input field for number<br/>
    <input phone-input="" type="tel" required="true" name="number" ng-model="employee.home.number" />
    <br/><br/>
    //custom field. format: area-number<br/>
  <input data-phone type="tel" required="true" ng-model="employee.home" />
  {{employee}}
</div>