Angularjs 如何在Angular指令中同时更新模型和视图值?
提前道歉,指令不是我的强项 我有一个简单的仅属性指令,其目的是在Angularjs 如何在Angular指令中同时更新模型和视图值?,angularjs,angularjs-directive,angular-ngmodel,Angularjs,Angularjs Directive,Angular Ngmodel,提前道歉,指令不是我的强项 我有一个简单的仅属性指令,其目的是在blur”对字段进行加密时,将字段中的字符串自动转换为HH:mm格式。这是指令: (function () { 'use strict'; angular .module('app.format-as-time') .directive('formatAsTime', timeDirective); timeDirective.$inject = [ 'i
blur
”对字段进行加密时,将字段中的字符串自动转换为HH:mm格式。这是指令:
(function () {
'use strict';
angular
.module('app.format-as-time')
.directive('formatAsTime', timeDirective);
timeDirective.$inject = [
'isValid'
];
function timeDirective (isValid) {
return {
require: 'ngModel',
restrict: 'A',
link: LinkFunction
};
function LinkFunction (scope, elem, attrs, ngModel) {
elem.bind('blur', function () {
var currentVal = ngModel.$modelValue,
formattedVal = '';
// Format something like 0115 to 01:15
if (currentVal.length === 4) {
formattedVal = currentVal.substr(0, 2) + ':' + currentVal.substr(2, 2);
// Format something like 115 to 01:15
} else if (currentVal.length === 3) {
formattedVal = '0' + currentVal.substr(0, 1) + ':' + currentVal.substr(1, 2);
// Format something like 15 to 00:15
} else if (currentVal.length === 2) {
formattedVal = '00:' + currentVal;
}
// If our formatted time is valid, apply it!
if (isValid.time(formattedVal)) {
scope.$applyAsync(function () {
ngModel.$viewValue = formattedVal;
ngModel.$render();
});
}
});
}
}
}());
以及相关视图:
<div ng-controller="TestController as test">
<input type="text"
maxlength="5"
placeholder="HH:mm"
ng-model="test.startTime"
format-as-time>
<button ng-click="test.getStartTime()">Get Start Time</button>
</div>
目前,该指令在视图中按预期工作,但我的控制器中的模型没有得到更新,即输入将包含01:15,但模型将console.log()
115
我试过使用:
scope: {
ngModel: '='
}
但这并没有起到任何作用
我这样做是否正确?如果是,我需要添加什么来确保模型和视图保持同步
如果我用了错误的方法,那么正确的方法是什么?问题在于这一行
ngModel.$viewValue=formattedVal
Angular有一个用于设置modelValue的管道,其中包括通过注册的$Parser和$Validator运行modelValue。设置该值的正确方法是调用将通过此管道运行该值的 isValid服务是什么样子的?isValid
只是一个工厂,它公开了一些函数来检查值是否有效isValid.time()
只是HH:mm字符串的一个简单正则表达式。有趣的是,这就是问题所在isValid.time()
在上面的指令中呈现视图时返回true。但是当尝试测试控制器模型时,isValid.time()
返回false,并显示模型包含预格式化的值。而不是ngModel。$viewValue=formattedVal代码>,请尝试ngModel.$setViewValue(formattedVal)
应该通过设置ngModel的普通模型管道来运行该值。我以前尝试过这个方法,但它不起作用,但我现在再次尝试,效果很好!我不想承认这一点,但我想我可能使用了ngModel.$setViewValue=formattedVal代码>当我在过去尝试这个时,难怪它不起作用。你介意把这作为一个答案,我会接受它吗?:)补充了一个答案。我很高兴它奏效了,但我觉得你不是我的强项,经常让我头晕目眩谢谢!我已经试过了,但没有成功,但我的语法不正确:ngModel.$setViewValue=formattedVal代码>
scope: {
ngModel: '='
}