1
我正在嘗試將AngularJS ui-mask和$ parser/$ formatters集成到同一個目錄中,以便有一個完整的指令來處理所有的我的日期輸入。 ui-mask似乎編譯正確,但我無法從鏈接函數的$ parser中獲取正確的模型值。
這裏是我的普拉克:https://plnkr.co/edit/DOA7h7XxrvngsMAIzc5P?p=preview
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-mask/1.8.1/mask.min.js"></script>
<body>
<script>
var app = angular.module('myApp', ['ui.mask']);
app.controller('myCtrl', function() {
var vm = this;
});
app.directive('myDate', ['$compile', '$filter', myDate]);
function myDate($compile, $filter) {
var directive = {
restrict: 'E',
require: 'ngModel',
scope: {
ngModel: "="
},
compile: compile,
link: link
};
return directive;
function compile(element, attrs) {
return function(scope, element, attrs) {
scope.keyup = function(key) {
if (key === 68) {
console.log("D key!");
}
};
var template = '<input class="' + attrs.class + '" ng-model="ngModel" ui-mask="99/99/9999" ng-keyup="keyup($event.keyCode)" type="text">';
element.html(template);
element.removeClass(attrs.class);
$compile(element.contents())(scope);
}
}
function link(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(data) { // view to model
var year = data.substr(-4);
var month = data.substr(2, 2);
var day = data.substr(0, 2);
var sep = '-';
data = (year && month && day) ? Date.parse(year + sep + month + sep + day) : '';
return data;
});
ngModel.$formatters.push(function(data) { // model to view
data = $filter('date')(data, 'dd/MM/yyyy');
return data;
});
}
}
</script>
<div ng-app="myApp" ng-controller="myCtrl as vm">
<my-date ng-model="vm.myValue"></my-date>
<p>myValue model: {{vm.myValue}}</p>
<i>(myValue correct for 01/01/1985: 473385600000)</i>
</div>
</body>
</html>
舉例來說,如果我寫的「1985年1月1日」我想在輸出有「473385600000」。
你能幫助我嗎?