指令不会更新范围变量

时间:2014-08-27 18:47:02

标签: angularjs

我有一个指令,将电话号码格式化为(xxx)xxx-xxxx。格式化按预期工作,但是,输入字段上的模型不会更新,除非您输入一个通过标准10的字符。因此,在用户输入10位数后,该数字会自动格式化输入字段内部。但是,除非输入其他字符,否则在ng-model上设置的范围变量不会保存格式。

这是指令:

(function (app) {
  'use strict';

  app.directive('formatPhone', [
    function() {
      return {
        require: 'ngModel',
        restrict: 'A',
        link: function(scope, elem) {
          elem.on('keyup', function() {
            var origVal = elem.val().replace(/[^\d]/g, '');
            if(origVal.length === 10) {
              var str = origVal.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
              var phone = str.slice(0, -1) + str.slice(-1);
              jQuery('#phonenumber').val(phone);
            }

          });
        }
      };
    }
  ]);
}(window.app));

这是输入字段,使用指令作为属性:

<input type="text" placeholder="Phone" name="phone" id="phonenumber" class="user-search-input create-short form-control" ng-model="userCtrl.userPost.user.phoneNumber" required format-phone>

我尝试过添加$watch,但也没有运气。

1 个答案:

答案 0 :(得分:2)

尝试

.directive('formatPhone', [
    function() {
        return {
            require: 'ngModel',
            restrict: 'A',
            priority:999999, //<-- Give a higher priority
            scope: {         
                model:'=ngModel' //<-- A 2 way binding to read actual bound value not the ngModel view value
            },
            link: function(scope, elem, attrs, ctrl) {
                var unwatch = scope.$watch('model', function(val){
                        if(!val) return;
                        var origVal = val.replace(/[^\d]/g, '');
                        if(origVal.length === 10) {
                            var str = origVal.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
                            var phone = str.slice(0, -1) + str.slice(-1);
                            ctrl.$setViewValue(phone);
                            ctrl.$render();
                            unwatch();
                        }
                 });
            }
        };
    }
]);