각도 부트스트랩 날짜 선택기 날짜 형식이 ng-model 값 형식을 지정하지 않음
각진 어플리케이션에서 부트스트랩 날짜 선택기를 사용하고 있습니다.그러나 바인드가 있는 ng-model의 기반이 되는 날짜 선택기에서 날짜를 선택하면 해당 ng-model을 하나의 날짜 형식 'MM/dd/yyy'로 원합니다.하지만 매번 이렇게 데이트가 된다.
"2009-02-03T18:30:00.000Z"
대신
02/04/2009
같은 plunkr 링크에 대해 plunkr을 작성했습니다.
나의 HTML과 컨트롤러 코드는 다음과 같다.
<!doctype html>
<html ng-app="plunker">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="DatepickerDemoCtrl">
<pre>Selected date is: <em>{{dt | date:'MM/dd/yyyy' }}</em></pre>
<p>above filter will just update above UI but I want to update actual ng-modle</p>
<h4>Popup</h4>
<div class="row">
<div class="col-md-6">
<p class="input-group">
<input type="text" class="form-control"
datepicker-popup="{{format}}"
ng-model="dt"
is-open="opened" min-date="minDate"
max-date="'2015-06-22'"
datepicker-options="dateOptions"
date-disabled="disabled(date, mode)"
ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)">
<i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
<!--<div class="row">
<div class="col-md-6">
<label>Format:</label> <select class="form-control" ng-model="format" ng-options="f for f in formats"><option></option></select>
</div>
</div>-->
<hr />
{{dt}}
</div>
</body>
</html>
각도 제어기
angular.module('plunker', ['ui.bootstrap']);
var DatepickerDemoCtrl = function ($scope) {
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.format = 'dd-MMMM-yyyy';
};
갱신하다
데이터를 게시하기 위해 아래 방법으로 전화드렸고 VAR은 날짜 선택 변수를 포함하는 900사이즈 배열입니다.
public SaveCurrentData(formToSave: tsmodels.ResponseTransferCalculationModelTS) {
var query = this.EntityQuery.from('SaveFormData').withParameters({
$method: 'POST',
$encoding: 'JSON',
$data: {
VAR: formToSave.VAR,
X: formToSave.X,
CurrentForm: formToSave.currentForm,
}
});
var deferred = this.q.defer();
this.manager.executeQuery(query).then((response) => {
deferred.resolve(response);
}, (error) => {
deferred.reject(error);
});
return deferred.promise;
}
비슷한 답변이 올라오긴 했지만 가장 쉽고 깔끔한 수정이라고 생각되는 것에 기여하고 싶습니다.Angular를 사용하는 경우UI 날짜 선택기에서 ng-Model의 초기 값이 포맷되지 않습니다.다음 지시문을 프로젝트에 추가하면 문제가 해결됩니다.
angular.module('yourAppName')
.directive('datepickerPopup', function (){
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, element, attr, controller) {
//remove the default formatter from the input directive to prevent conflict
controller.$formatters.shift();
}
}
});
난 이 용액을 Github Angular에서 찾았다.UI 문제, 따라서 모든 공적은 저쪽 사람들에게 돌아간다.
아래와 같이 $pars를 사용하시면 해결이 됩니다.
window.module.directive('myDate', function(dateFilter) {
return {
restrict: 'EAC',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue,'yyyy-MM-dd');
});
}
};
});
HTML:
<p class="input-group datepicker" >
<input
type="text"
class="form-control"
name="name"
datepicker-popup="yyyy-MM-dd"
date-type="string"
show-weeks="false"
ng-model="data[$parent.editable.name]"
is-open="$parent.opened"
min-date="minDate"
close-text="Close"
ng-required="{{editable.mandatory}}"
show-button-bar="false"
close-on-date-selection="false"
my-date />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="openDatePicker($event)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</p>
저도 같은 문제에 부딪혀 몇 시간 동안 로그 기록과 조사를 한 후 수정했습니다.
이 값은 처음으로 달력 선택기에서 설정되며 $viewValue는 문자열이므로 dateFilter에 그대로 표시됩니다.날짜 오브젝트로 해석했을 뿐입니다.
ui-bootstrap-tpls 파일에서 해당 블록을 검색합니다.
ngModel.$render = function() {
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
다음으로 대체:
ngModel.$render = function() {
ngModel.$viewValue = new Date(ngModel.$viewValue);
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
이것이 도움이 되기를 바랍니다:)
format 통해 datepicker-popup는 표시되는 날짜의 형식입니다.기초가 되는 것ngModel②날짜 ②날짜.표시하려고 하면 기본 표준 준거 랩렌테이션으로 표시됩니다.
대로 수 요.date가 있는 는, 「필터」를 할 수 있습니다.$filter을 「조종하다」라고 .$filter('date')(date, format)날짜 필터 문서도 참조하십시오.
날짜 선택 지시문 내의 값을 선택한 후 포맷터를 사용할 수 있습니다.예를들면
angular.module('foo').directive('bar', function() {
return {
require: '?ngModel',
link: function(scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.push(function(value) {
if (value) {
// format and return date here
}
return undefined;
});
}
};
});
이미 많은 답을 썼으니, 제 의견은 이렇습니다.
Angular 1.5.6 & ui-bootstrap 1.3.3 에서는, 이것을 모델에 추가하는 것만으로 완료됩니다.
ng-model-options="{timezone: 'UTC'}"
주의: T00:00:00.000Z의 추가 시간을 신경 쓰지 않고 1일 후가 걱정되는 경우에만 사용하십시오.
갱신된 Plunkr 여기:
http://plnkr.co/edit/nncmB5EHEUkZJXRwz5QI?p=preview
제안하신 모든 솔루션이 효과가 있었던 것은 아니지만, 가장 가까운 솔루션은 @Rishii의 솔루션이었습니다.
AngularJS 1.4.4와 UI Bootstrap 0.13.3을 사용하고 있습니다.
.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
return {
restrict: 'EAC',
require: 'ngModel',
priority: 1,
link: function(scope, element, attrs, ngModel) {
var dateFormat = 'yyyy-MM-dd';
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue, dateFormat);
});
ngModel.$validators.date = function (modelValue, viewValue) {
var value = modelValue || viewValue;
if (!attrs.ngRequired && !value) {
return true;
}
if (angular.isNumber(value)) {
value = new Date(value);
}
if (!value) {
return true;
}
else if (angular.isDate(value) && !isNaN(value)) {
return true;
}
else if (angular.isString(value)) {
var date = dateParser.parse(value, dateFormat);
return !isNaN(date);
}
else {
return false;
}
};
}
};
}])
JSP 파일에 아래 코드를 추가하면 수정할 수 있습니다.이제 모델과 UI 값이 모두 동일합니다.
<div ng-show="false">
{{dt = (dt | date:'dd-MMMM-yyyy') }}
</div>
ng-model 기본 날짜 형식을 변경하는 단계
다른 날짜 형식에 대해서는 여기서 jqueryui 날짜 선택기 날짜 형식 값을 확인합니다. 예를 들어, 나는 dd/mm/yy를 사용했습니다.
angularjs 지시문 작성
angular.module('app', ['ui.bootstrap']).directive('dt', function () {
return {
restrict: 'EAC',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
ngModel.$parsers.push(function (viewValue) {
return dateFilter(viewValue, 'dd/mm/yy');
});
}
}
});
쓰기 날짜 필터 함수
function dateFilter(val,format) {
return $.datepicker.formatDate(format,val);
}
html 페이지에 ng-modal 속성을 입력합니다.
<input type="text" class="form-control" date-type="string" uib-datepicker-popup="{{format}}" ng-model="src.pTO_DATE" is-open="popup2.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" show-button-bar="false" show-weeks="false" dt />
datepicker(및 datepicker-popup) 디렉티브에서는 ng-model이 Date 객체여야 합니다.여기에 기재되어 있습니다.
ng-model을 특정 형식의 문자열로 만들려면 래퍼 디렉티브를 작성해야 합니다.다음으로 예시(플런커)를 나타냅니다.
(function () {
'use strict';
angular
.module('myExample', ['ngAnimate', 'ngSanitize', 'ui.bootstrap'])
.controller('MyController', MyController)
.directive('myDatepicker', myDatepickerDirective);
MyController.$inject = ['$scope'];
function MyController ($scope) {
$scope.dateFormat = 'dd MMMM yyyy';
$scope.myDate = '30 Jun 2017';
}
myDatepickerDirective.$inject = ['uibDateParser', '$filter'];
function myDatepickerDirective (uibDateParser, $filter) {
return {
restrict: 'E',
scope: {
name: '@',
dateFormat: '@',
ngModel: '='
},
required: 'ngModel',
link: function (scope) {
var isString = angular.isString(scope.ngModel) && scope.dateFormat;
if (isString) {
scope.internalModel = uibDateParser.parse(scope.ngModel, scope.dateFormat);
} else {
scope.internalModel = scope.ngModel;
}
scope.open = function (event) {
event.preventDefault();
event.stopPropagation();
scope.isOpen = true;
};
scope.change = function () {
if (isString) {
scope.ngModel = $filter('date')(scope.internalModel, scope.dateFormat);
} else {
scope.ngModel = scope.internalModel;
}
};
},
template: [
'<div class="input-group">',
'<input type="text" readonly="true" style="background:#fff" name="{{name}}" class="form-control" uib-datepicker-popup="{{dateFormat}}" ng-model="internalModel" is-open="isOpen" ng-click="open($event)" ng-change="change()">',
'<span class="input-group-btn">',
'<button class="btn btn-default" ng-click="open($event)"> <i class="glyphicon glyphicon-calendar"></i> </button>',
'</span>',
'</div>'
].join('')
}
}
})();
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body ng-app="myExample">
<div ng-controller="MyController">
<p>
Date format: {{dateFormat}}
</p>
<p>
Value: {{myDate}}
</p>
<p>
<my-datepicker ng-model="myDate" date-format="{{dateFormat}}"></my-datepicker>
</p>
</div>
</body>
</html>
버그를 회피하기 위한 새로운 디렉티브를 정의하는 것은 그다지 이상적이지 않습니다.
날짜 선택기에는 이후 날짜가 올바르게 표시되므로 간단한 회피책 중 하나는 모델 변수를 먼저 null로 설정한 후 잠시 후 현재 날짜로 설정하는 것입니다.
$scope.dt = null;
$timeout( function(){
$scope.dt = new Date();
},100);
위의 답변을 확인한 후, 저는 이것을 생각해 냈고, 당신의 마크업에 추가 속성을 추가하지 않고도 완벽하게 작동했습니다.
angular.module('app').directive('datepickerPopup', function(dateFilter) {
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue, 'yyyy-MM-dd');
});
}
}
});
마침내 나는 위의 문제를 해결했다.angular-strap은 제가 예상한 것과 똑같은 기능을 가지고 있습니다.신청하는 것만으로date-format="MM/dd/yyyy" date-type="string"주어진 형식으로 ng-model을 업데이트 하는 나의 예상된 행동을 얻었습니다.
<div class="bs-example" style="padding-bottom: 24px;" append-source>
<form name="datepickerForm" class="form-inline" role="form">
<!-- Basic example -->
<div class="form-group" ng-class="{'has-error': datepickerForm.date.$invalid}">
<label class="control-label"><i class="fa fa-calendar"></i> Date <small>(as date)</small></label>
<input type="text" autoclose="true" class="form-control" ng-model="selectedDate" name="date" date-format="MM/dd/yyyy" date-type="string" bs-datepicker>
</div>
<hr>
{{selectedDate}}
</form>
</div>
여기 동작하고 있는 plunk 링크가 있습니다.
언급URL : https://stackoverflow.com/questions/24198669/angular-bootstrap-datepicker-date-format-does-not-format-ng-model-value
'programing' 카테고리의 다른 글
| JSON 피드에 값이 존재하는지 확인하는 더 나은 방법 (0) | 2023.03.26 |
|---|---|
| 스프링 부트에 여러 크로스 오리진 URL 추가 (0) | 2023.03.26 |
| 응답 라우터: 정의되지 않은 속성 'pathname'을 읽을 수 없습니다. (0) | 2023.03.26 |
| "Expected to return a value at end of arrow function" 경고를 수정하려면 어떻게 해야 합니까? (0) | 2023.03.26 |
| 속성을 통해 복제 세트를 사용하도록 spring-data-mongodb를 구성하는 방법 (0) | 2023.03.26 |