ui-bootstrap datepicker의 angularJs 래퍼 디렉티브를 작성하려면 어떻게 해야 합니까?
날짜 필드를 표시하기 위해 ui.bootstrap.datepicker 디렉티브를 사용하고 있습니다.그러나 대부분의 경우 동일한 설정이 필요합니다.팝업과 팝업 버튼이 함께 오길 바라며, 텍스트의 독일어 이름도 원합니다.버튼과 텍스트, 포맷에 같은 코드가 계속 생성되기 때문에 반복하지 않기 위해 제가 직접 지시문을 작성했습니다.
여기 내 지시사항을 담은 plunkr이 있다.하지만 내가 잘못하고 있는 것 같아.내 지시문을 사용하지 않는 "날짜 1" 날짜 선택기를 사용하여 날짜를 선택하면 모든 작업이 정상적으로 수행됩니다.날짜 2도 마찬가지입니다만, 입력 필드에 입력한 템플릿(또는 예상한 다른 값)에 따라 날짜를 표시하는 대신,.toString() 오브젝트의 "DateFri Apr 03 2015 00:00:00 GMT+0200 (CEST)를 참조해 주세요.
제 지시는 다음과 같습니다.
angular.module('ui.bootstrap.demo').directive('myDatepicker', function($compile) {
var controllerName = 'dateEditCtrl';
return {
restrict: 'A',
require: '?ngModel',
scope: true,
link: function(scope, element) {
var wrapper = angular.element(
'<div class="input-group">' +
'<span class="input-group-btn">' +
'<button type="button" class="btn btn-default" ng-click="' + controllerName + '.openPopup($event)"><i class="glyphicon glyphicon-calendar"></i></button>' +
'</span>' +
'</div>');
function setAttributeIfNotExists(name, value) {
var oldValue = element.attr(name);
if (!angular.isDefined(oldValue) || oldValue === false) {
element.attr(name, value);
}
}
setAttributeIfNotExists('type', 'text');
setAttributeIfNotExists('is-open', controllerName + '.popupOpen');
setAttributeIfNotExists('datepicker-popup', 'dd.MM.yyyy');
setAttributeIfNotExists('close-text', 'Schließen');
setAttributeIfNotExists('clear-text', 'Löschen');
setAttributeIfNotExists('current-text', 'Heute');
element.addClass('form-control');
element.removeAttr('my-datepicker');
element.after(wrapper);
wrapper.prepend(element);
$compile(wrapper)(scope);
scope.$on('$destroy', function () {
wrapper.after(element);
wrapper.remove();
});
},
controller: function() {
this.popupOpen = false;
this.openPopup = function($event) {
$event.preventDefault();
$event.stopPropagation();
this.popupOpen = true;
};
},
controllerAs: controllerName
};
});
그게 내가 쓰는 방법이야
<input my-datepicker="" type="text" ng-model="container.two" id="myDP" />
(개념은 이 답변에서 영감을 얻었다)
angular 1.3을 사용하고 있습니다(플런커는 1.2에 있습니다.이는 angular-ui-bootstrap datepicker 매뉴얼에서 플런커를 포크했기 때문입니다).나는 이것이 아무런 차이가 없기를 바란다.
입력된 텍스트 출력이 잘못된 이유와 올바르게 실행되는 방법은 무엇입니까?
갱신하다
그동안 나는 약간의 진전이 있었다.컴파일 및 링크에 대한 자세한 내용을 읽은 후 이 플런커에서는 링크 함수가 아닌 컴파일 함수를 사용하여 DOM을 조작합니다.나는 아직도 이 문서에서 발췌한 내용에 약간 혼란스럽다.
주의: 템플릿이 복제되어 있는 경우 템플릿인스턴스와 링크인스턴스는 다른 오브젝트일 수 있습니다.따라서 컴파일 함수 내의 모든 클론된 DOM 노드에 적용되는 DOM 변환 이외의 작업을 수행하는 것은 안전하지 않습니다.특히 DOM 청취자 등록은 컴파일 함수가 아닌 링크 함수로 이루어져야 합니다.
특히 클론된 모든 DOM 노드에 적용되는 것은 어떤 의미인지 궁금합니다.원래 "DOM 템플릿의 모든 클론 적용"을 의미한다고 생각했지만 그렇지 않은 것 같습니다.
어쨌든, 나의 새로운 컴파일 버전은 크롬으로 잘 동작한다.Firefox에서는 먼저 달력 보기를 사용하여 날짜를 선택해야 합니다. 그 후 모든 것이 정상적으로 작동합니다(날짜 선택기의 날짜 분석기에서 null(plunkr)로 변경되면 Firefox의 문제가 자동으로 해결됩니다).그래서 이것도 최신이 아니다.그리고 추가로 나는ng-model2ng-model컴파일 중에 이름을 바꿉니다.내가 이렇게 하지 않으면 모든 것이 여전히 망가진다.왜 그랬는지 모르겠어.
솔직히 말하면, 왜 그런 일이 일어났는지, 그리고 왜 데이트 상대를 '스트링 편집'하게 했는지 잘 모르겠어요.
하고 불필요한를 많이 수 있는 .$compile 변경, 스코프 , 「」, 「」, 「」, 「」,require 다이렉트 스코프를 는 없다고하기 때문입니다. 를 일으킬 가능성이 있기 때문입니다.모든 다이렉트 사용법이 부모 범위를 알 필요는 없다고 생각하기 때문에 격리된 범위를 사용했습니다.이는 앞으로 악성 버그가 발생할 수 있기 때문입니다.변경된 지시사항은 다음과 같습니다.
angular.module('ui.bootstrap.demo').directive('myDatepicker', function() {
return {
restrict: 'A',
scope: {
model: "=",
format: "@",
options: "=datepickerOptions",
myid: "@"
},
templateUrl: 'datepicker-template.html',
link: function(scope, element) {
scope.popupOpen = false;
scope.openPopup = function($event) {
$event.preventDefault();
$event.stopPropagation();
scope.popupOpen = true;
};
scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
scope.opened = true;
};
}
};
});
HTML 사용법은 다음과 같습니다.
<div my-datepicker model="container.two"
datepicker-options="dateOptions"
format="{{format}}"
myid="myDP">
</div>
편집: 추가했습니다.id명령어에 대한 매개 변수입니다.이치노
디렉티브 정의에 다음 2 행을 추가하면 디렉티브가 기능합니다.
return {
priority: 1,
terminal: true,
...
}
이것은 명령이 실행되는 순서와 관련이 있습니다.
그래서 당신의 코드로
<input my-datepicker="" type="text" ng-model="container.two" id="myDP" />
다음 두 가지 지시사항이 있습니다.ngModel ★★★★★★★★★★★★★★★★★」myDatepicker ngModel이실행하기 전에 자신의 할 수 우선순위에 따라 ngModel보다 먼저 자신의 디렉티브를 실행할 수 있습니다.
@omri-aharon의 답변이 가장 좋다고 생각합니다만, 여기서 언급되지 않은 몇 가지 개선점을 지적하고 싶습니다.
갱신된 PLunkr
구성을 사용하면 다음과 같이 형식 및 텍스트 옵션 등의 옵션을 균일하게 설정할 수 있습니다.
angular.module('ui.bootstrap.demo', ['ui.bootstrap'])
.config(function (datepickerConfig, datepickerPopupConfig) {
datepickerConfig.formatYear='yy';
datepickerConfig.startingDay = 1;
datepickerConfig.showWeeks = false;
datepickerPopupConfig.datepickerPopup = "shortDate";
datepickerPopupConfig.currentText = "Heute";
datepickerPopupConfig.clearText = "Löschen";
datepickerPopupConfig.closeText = "Schließen";
});
더 명확하고 쉽게 업데이트할 수 있습니다.또, 디렉티브, 템플릿, 마크업을 큰폭으로 심플화할 수 있습니다.
커스텀 디렉티브
angular.module('ui.bootstrap.demo').directive('myDatepicker', function() {
return {
restrict: 'E',
scope: {
model: "=",
myid: "@"
},
templateUrl: 'datepicker-template.html',
link: function(scope, element) {
scope.popupOpen = false;
scope.openPopup = function($event) {
$event.preventDefault();
$event.stopPropagation();
scope.popupOpen = true;
};
scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
scope.opened = true;
};
}
};
});
템플릿
<div class="row">
<div class="col-md-6">
<p class="input-group">
<input type="text" class="form-control" id="{{myid}}" datepicker-popup ng-model="model" is-open="opened" ng-required="true" />
<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>
사용방법
<my-datepicker model="some.model" myid="someid"></my-datepicker>
angular-contract_de. angular-contract_de. angular-contract_de. angular-contract_de. angular-contracturn_de. angular-contracturna. 날짜 되게 사용할 수 .'shortDate'독일어 월 및 일 이름을 강제로 사용합니다.
여기 내 몽키 패치가 있어
http://plnkr.co/edit/9Up2QeHTpPvey6jd4ntJ?p=preview
기본적으로 제가 한 일은 날짜인 당신의 모델을 변경해서 명령어를 사용하여 포맷된 문자열을 반환하는 것입니다.
.directive('dateFormat', function (dateFilter) {
return {
require:'^ngModel',
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
viewValue.toString = function() {
return dateFilter(this, attrs.dateFormat);
};
return viewValue;
});
}
};
});
합격해야 합니다.date-format에 대한 속성input태그를 붙입니다.
내가 너라면 그렇게까지 복잡한 지시를 내리지는 않을 거야.간단하게 추가하겠습니다.<datepicker>에 첨부되어 있습니다.input동일한 ng-model로 태그를 지정하고 버튼으로 표시/숨김을 제어합니다.내 plunker부터 네 옵션을 시험해봐
디렉티브를 작성하는 것이 Atribute를 추가하는 편리한 경우, 원래의 입력에 다음의 2개의 디렉티브를 설정할 수 있습니다.
<input my-datepicker="" datepicker-popup="{{ format }}" type="text" ng-model="container.two" id="myDP" />
그 후, 복수의 격리 범위를 변경해 회피합니다.scope: true로.scope: false에서myDatepicker지시.
이 방법은 유효하며, 날짜 입력을 원하는 형식으로 변경하는 추가 지시문을 작성하는 것이 좋습니다.
http://plnkr.co/edit/23QJ0tjPy4zN16Sa7svB?p=preview
지시문 내에서 Atribut을 추가하면 이 문제가 발생합니다.같은 입력에 2개의 날짜 선택자가 있는 것 같습니다.하나는 포맷으로, 다른 하나는 디폴트로 나중에 적용됩니다.
eui-bootstrap datepicker 컴포넌트와 함께 moment.js를 사용하여 날짜 시간 형식에 대한 포괄적인 패턴 집합을 제공하는 지시문을 만듭니다.격리된 범위 내에서 원하는 시간 형식을 사용할 수 있습니다.
Typescript의 실장에 관심이 있는 유저(@jme11의 코드에 근거하고 있지 않은 경우):
지시:
'use strict';
export class DatePickerDirective implements angular.IDirective {
restrict = 'E';
scope={
model: "=",
myid: "@"
};
template = require('../../templates/datepicker.tpl.html');
link = function (scope, element) {
scope.altInputFormats = ['M!/d!/yyyy', 'yyyy-M!-d!'];
scope.popupOpen = false;
scope.openPopup = function ($event) {
$event.preventDefault();
$event.stopPropagation();
scope.popupOpen = true;
};
scope.open = function ($event) {
$event.preventDefault();
$event.stopPropagation();
scope.opened = true;
};
};
public static Factory() : angular.IDirectiveFactory {
return () => new DatePickerDirective();
}
}
angular.module('...').directive('datepicker', DatePickerDirective.Factory())
템플릿:
<p class="input-group">
<input type="text" class="form-control" id="{{myid}}"
uib-datepicker-popup="MM/dd/yyyy" model-view-value="true"
ng-model="model" ng-model-options="{ getterSetter: true, updateOn: 'blur' }"
close-text="Close" alt-input-formats="altInputFormats"
is-open="opened" ng-required="true"/><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>
사용방법:
<datepicker model="vm.FinishDate" myid="txtFinishDate"></datepicker>
저는 이 일을 (어떤 해킹을) 하려고 노력했지만, 당신이 원하는 것은 아닐지도 모르지만, 단지 몇 가지 대략적인 아이디어일 뿐입니다.그래서 당신은 여전히 그것을 조금 수정해야 합니다.문제는 다음과 같습니다.
`http://plnkr.co/edit/aNiL2wFz4S0WPti3w1VG?p=preview'
기본적으로 지시 범위를 변경하고 scope var container.2에 대한 watch도 추가했습니다.
언급URL : https://stackoverflow.com/questions/29562213/how-to-create-an-angularjs-wrapper-directive-for-a-ui-bootstrap-datepicker
'source' 카테고리의 다른 글
| MongoDb: $push/$addtoset의 차이 (0) | 2023.04.02 |
|---|---|
| React 구성 요소의 렌더링 지연 (0) | 2023.04.02 |
| Spring Cloud Config 서버에 특정 브랜치에서 구성을 체크아웃하도록 요청하려면 어떻게 해야 합니까? (0) | 2023.04.02 |
| 반응 네이티브 응용 프로그램에서 클릭 기능이 작동하지 않습니다. (0) | 2023.04.02 |
| Mongoose 하위 문서 vs 중첩된 스키마 (0) | 2023.04.02 |