[英]Directive doesn't update scope variable
我有一条指令将电话号码的格式设置为(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
,也没有运气。
尝试像
.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();
}
});
}
};
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.