angularjs自定义指令中的ng-change函数在用户第二次输入后更新输入值 [英] ng-change function in angularjs custom directive updating input value after second input from the user
问题描述
此功能正常工作但当用户输入第一个数字到文本字段时,它作为空值传递给控制器,在第二次输入后,它将第一个输入传递给控制器。我想在第一次输入时使用正确的值而不是空值来控制值。
This function works fine but when user enter first digit to text field it pass to the controller as a empty value and after second input it passes first input to the controller. I want to take value to controller on first input with correct value instead of empty value.
我已经为数字验证创建了自定义指令
I have created custom directive for number validation
app.directive('faxFormat', ['$filter', function($filter) {
function link(scope, element, attributes) {
// scope.inputValue is the value of input element used in template
scope.inputValue = scope.phonenumberModel;
scope.$watch('inputValue', function(value, oldValue) {
value = String(value);
var number = value.replace(/[^0-9]+/g, '');
// scope.phonenumberModel = number;
scope.inputValue = $filter('phonenumber')(number);
scope.phonenumberModel = scope.inputValue;
});
scope.$watch('phonenumberModel', function(value, oldValue) {
scope.inputValue = scope.phonenumberModel;
});
// element.bind('click', function(){
// scope.method();
// });
scope.phoneFocused = function(){
scope.method();
}
}
return {
link: link,
//restrict: 'A',
//require: 'ngModel'
restrict: 'E',
scope: {
method: '&',
phonenumberPlaceholder: '=placeholder',
phonenumberModel: '=model',
myid: '=myid'
},
template: '<input ng-model="inputValue" type="tel" id="{{myid}}" class="phonenumber {{cls}}" ng-trim="false" placeholder="{{phonenumberPlaceholder}}" title="Phonenumber (Format:999-999-9999 or 1-999-999-9999)" ng-change="phoneFocused()">'
};
}]);
这是我的控制器
$scope.removePhoneErrorHighlight = function() {
var fax =$scope.phoneData.phoneNumber;
console.log(fax);
}
这是我的html代码
<fax-format class="faxFormat" myid="'accountPhone'" placeholder="'555-555-5555'" model="phoneData.phoneNumber" method="removePhoneErrorHighlight()" data-ng-focus="removePhoneErrorHighlight()"></fax-format>
推荐答案
尝试这种方法
link: function (scope, element, attrs, ngModelCtrl) {
// on change of modal
element.on("change", function (e) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(element.val());
});
});
}
如果DOM发生变化,将更新后的值设置为范围。
setting the updated value to the scope if the DOM changes.
,在指令中包含require:'ngModel'。
for the controller instance, include require: 'ngModel' in your directive.
如果是element.on(更改, ...(这个语法不确定)
如果它不起作用请告诉我。
if element.on("change", ... (this syntax am not sure) if it is not working pls let me know.
这篇关于angularjs自定义指令中的ng-change函数在用户第二次输入后更新输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!