我想創建一個指令,允許用戶以各種格式輸入日期。當底層模型發生變化時(無論是通過直接用戶輸入還是以編程方式),我希望它以規範化的格式顯示日期。
這個「在野外」的例子是Google Flights上的離開和返回日期輸入。
這是我的代碼(根本不起作用)。
VIEW
<input type="text" ng-model="params.departDate"
date-input display-format="{Weekday} {d} {Month}, {yyyy}">
控制器
app.controller('MainCtrl', function($scope) {
$scope.params = {
departDate: new Date()
};
$scope.isDate = function() {
return $scope.params.departDate instanceof Date;
}
});
DIRECTIVE
app.directive("dateInput", function() {
return {
require: 'ngModel',
scope: {
displayFormat: '@'
},
link: function (scope, element, attrs, ngModel) {
ngModel.$parsers.push(function (viewVal) {
if (viewVal) {
// Using sugar.js for date parsing
var parsedValue = Date.create(viewVal);
if (parsedValue.isValid()) {
ngModel.$setValidity("date", true);
return parsedValue;
}
}
ngModel.$setValidity("date", false);
return viewVal;
});
ngModel.$formatters.unshift(function (modelVal) {
if (modelVal){
// Using sugar.js for date formatting
var date = Date.create(modelVal);
if (date.isValid()) {
return date.format(scope.displayFormat || '{Weekday} {d} {Month}, {yyyy}')
}
}
return modelVal;
});
}
};
})
這還不來Ç失去了我所期望的工作。我究竟做錯了什麼?
這裏有一個PLUNKR:http://plnkr.co/edit/583yOD6aRhRD8Y2bA5gU?p=preview
NG-模型和隔離範圍不拌勻:http://stackoverflow.com/問題/ 11896732/ngmodel-和componen t -with-isolated-scope我建議不要在你的指令中創建任何範圍,並使用attrs:'var displayFormat = attrs.displayFormat'來訪問display-format屬性。 –
謝謝1000倍!你剛給我一臺500美元的新顯示器,我正要用挫敗感砸碎一塊磚頭。 – jessegavin