AngularJS - 指令格式化程序不适用于空值
AngularJS - Directive formatter is not working for null value
您好。在我的例子中,当 ngModel 值(下面的 val)不为空时,我可以正常使用格式化程序。 (< input > 标签将被格式化。)
ngModelCtrl.$formatters.push(function (val) {
if (val) {
console.log('log positive');
return 'Record found';
} else {
console.log('log negative');
return 'No record';
}
});
这意味着只有当 val 包含一个值时,< input > 标签才会被格式化。但是,我发现虽然显示了 'log negative',但是 标签也没有被格式化。
请问有什么办法可以解决这个问题吗?提前致谢。
更新 1
这是我使用的完整代码
HTML
<div ng-app="myApp" ng-controller="memberDetailCtrl" ng-init="ent.lastDepositDate=null;">
<tit-date title="depositDate" ng-model="ent.lastDepositDate"></tit-date></tit-txt>
</div>
Javascript
angular.module("myApp", [])
.controller("memberDetailCtrl", function ($scope) {
})
.directive('titDate', function () {
return {
restrict: 'E',
scope: {
title: '@',
fieldName: '@',
ngModel: '='
},
template: '<div><span>{{title}}: </span><input ng-model="ngModel" datepicker readonly /></div>'
};
})
.directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function (val) {
if (val) {
console.log('log positive');
return 'Record found';
} else {
console.log('log negative');
return 'No record';
}
});
}
}
});
感谢大哥,终于发现这是AngularJS1.3.0的bug。一旦我将它升级到当前版本。
您好。在我的例子中,当 ngModel 值(下面的 val)不为空时,我可以正常使用格式化程序。 (< input > 标签将被格式化。)
ngModelCtrl.$formatters.push(function (val) {
if (val) {
console.log('log positive');
return 'Record found';
} else {
console.log('log negative');
return 'No record';
}
});
这意味着只有当 val 包含一个值时,< input > 标签才会被格式化。但是,我发现虽然显示了 'log negative',但是 标签也没有被格式化。
请问有什么办法可以解决这个问题吗?提前致谢。
更新 1
这是我使用的完整代码
HTML
<div ng-app="myApp" ng-controller="memberDetailCtrl" ng-init="ent.lastDepositDate=null;">
<tit-date title="depositDate" ng-model="ent.lastDepositDate"></tit-date></tit-txt>
</div>
Javascript
angular.module("myApp", [])
.controller("memberDetailCtrl", function ($scope) {
})
.directive('titDate', function () {
return {
restrict: 'E',
scope: {
title: '@',
fieldName: '@',
ngModel: '='
},
template: '<div><span>{{title}}: </span><input ng-model="ngModel" datepicker readonly /></div>'
};
})
.directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function (val) {
if (val) {
console.log('log positive');
return 'Record found';
} else {
console.log('log negative');
return 'No record';
}
});
}
}
});
感谢大哥,终于发现这是AngularJS1.3.0的bug。一旦我将它升级到当前版本。