假设我有自定义方向控制数字的数量。
myApp.directive('myMaxlength', ['$compile', '$log', function($compile, $log) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
attrs.$set("ngTrim", "false");
var maxlength = parseInt(attrs.myMaxlength, 10);
ctrl.$parsers.push(function (value) {
$log.info("In parser function value = [" + value + "].");
if (value.length > maxlength)
{
$log.info("The value [" + value + "] is too long!");
value = value.substr(0, maxlength);
ctrl.$setViewValue(value);
ctrl.$render();
$log.info("The value is now truncated as [" + value + "].");
}
return value;
});
}
};
}]);
例如,当我写my-maxlength="10"
时,用户不能写更多
问题是当我将此指令添加到angularUi Datepicker
时,我收到错误:
Error: value is null .link/<@http://andcweb.com/App/Directives/maxlength.js:10:1 NgModelController
HTML
<input type="text" name="birth" class="form-control"
datepicker-popup-persian="{{format}}"
tabindex="7"
ng-model="requesterViewModel.BirthDate"
is-open="datePicker.opened"
datepicker-options="dateOptions"
date-disabled="disabled(date, mode)"
close-text="بسته"
min-date="minDate" max-date="dt" my-maxlength="6" />
<span class="input-group-btn">
<button type="button" class="btn btn-default iconBtn" ng-click="openPersian($event)"><i class="fa fa-calendar"></i></button>
</span>
有什么想法吗?非常感谢
答案 0 :(得分:0)
请仔细阅读错误消息:
Error: value is null .link/<@http://andcweb.com/App/Directives/maxlength.js:10:1 NgModelController
此消息提供发生错误的确切行号以及错误的明确说明。
if (value.length > maxlength) { ... }
应该是:
if (value && value.length > maxlength) { ... }
否则,当$ viewValue为length
时,您可能会尝试阅读null
的{{1}}属性。