source

모델이 각도 입력의 날짜 개체가 아닙니다.JS

goodcode 2023. 2. 14. 23:09
반응형

모델이 각도 입력의 날짜 개체가 아닙니다.JS

각도 사용JS 입력을 사용하여 날짜를 표시하려고 합니다.type=date:

<input ng-model="campaign.date_start" type="date">

단, 이로 인해 다음 오류가 발생합니다.

Error: error:datefmt
Model is not a date object

실제 날짜는 다음 형식의 JSON API에서 가져옵니다.

date_start": "2014-11-19"

필터를 사용하면 해결할 수 있을 것 같았지만, 이것은 동작하지 않고, 같은 에러가 표시됩니다.

 <input ng-model="campaign.date_start | date" type="date">

문자열도 날짜로 변환하려고 했지만 다시 같은 오류가 나타납니다.

 $scope.campaign.date_start = Date(campaign.date_start);

또 뭐가 있을까요?

이 디렉티브를 사용할 수 있습니다.

angular.module('app')
.directive("formatDate", function(){
  return {
   require: 'ngModel',
    link: function(scope, elem, attr, modelCtrl) {
      modelCtrl.$formatters.push(function(modelValue){
        return new Date(modelValue);
      })
    }
  }
})

html에서

<input type="date" ng-model="date" format-date>

$formatters

Array.<Function>

모델 값이 변경될 때마다 파이프라인으로 실행할 함수 배열입니다.함수는 역배열 순서로 호출되며 각각 값이 다음 배열로 전달됩니다.마지막 반환값은 실제 DOM 값으로 사용됩니다.컨트롤에 표시할 값의 형식을 지정하거나 변환하는 데 사용됩니다.

인스턴스화해야 합니다.campaign.date_start와 함께Date함수로 사용하지 않습니다.

다음과 같이 표시됩니다(작은 데모).

$scope.campaign.date_start = new Date(campaign.date_start);

cs1707날짜의 범위 값이 다음과 같은 경우를 제외하고 님의 지시문은 훌륭합니다.null또는undefined그러면 다음 날짜를 초기화합니다.1/1/1970이것은 아마 대부분의 사람들에게 최적이지는 않을 것이다.

다음은 의 변경된 버전입니다.cs1707를 남기는 지령null/undefined모델화:

angular.module('app').directive("formatDate", function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attr, modelCtrl) {
            modelCtrl.$formatters.push(function(modelValue) {
                if (modelValue){
                    return new Date(modelValue);
                }
                else {
                    return null;
                }
            });
        }
    };
});

html에서

<input type="date" ng-model="date" format-date>

기타 옵션

이 값을 유형 날짜의 모든 입력에 적용할 경우 format-date 속성을 각 입력 요소에 추가할 필요가 없습니다.다음 지시문을 사용할 수 있습니다(다른 커스텀 지시문과 예기치 않은 방식으로 상호 작용할 수 있으므로 주의하십시오).

angular.module('app').directive("input", function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attr, modelCtrl) {
            if (attr['type'] === 'date'){
                modelCtrl.$formatters.push(function(modelValue) {
                    if (modelValue){
                        return new Date(modelValue);
                    }
                    else {
                        return null;
                    }
                });
            }

        }
    };
});

html에서

<input type="date" ng-model="date">

또 다른 직접적인 솔루션은 다음과 같습니다.

//inside directives.js
.directive('dateField', function () {
    return {
        restrict: ' E',
        scope: {
            ngBind: '=ngModel',
            ngLabel: '@'
        },
        replace: true,
        require: 'ngModel',
        controller: function ($scope) {
            if ($scope.ngBind != null) {
                var pattern = /Date\(([^)]+)\)/;
                var results = pattern.exec($scope.ngBind);
                var dt = new Date(parseFloat(results[1]));
                $scope.ngBind = dt;
            };
        },
        templateUrl: 'templates/directives/dateField.html'
    }
})
;

다음과 같은 지시 템플릿을 추가합니다.

<!-- app.directives templates/directives/dateField -->
<script id="templates/directives/dateField.html" type="text/ng-template">    
    <label class="item item-input item-stacked-label ">
        <span class="input-label">{{ngLabel}}</span>
        <input type="date" placeholder="" ng-model="ngBind" />
    </label>
</script>

그리고 그것을 사용한다.

<date-field ng-label="This date..." ng-model="datajson.do.date"></date-field>

행운을 빕니다.

지시어를 사용하여 기본 각도 포맷터/파서 재설정 방법ngModelCtrl.$formatters.length = 0; ngModelCtrl.$parsers.length = 0;

효과가 있다input[type="date"]게다가input[type="time"]. Cordova 앱에서도 잘 동작합니다.

HTML:

<input date-input type="time" ng-model="created_time">

각도 지시:

app.directive('dateInput', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
            //Angular 1.3 insert a formater that force to set model to date object, otherwise throw exception.
            //Reset default angular formatters/parsers
            ngModelCtrl.$formatters.length = 0;
            ngModelCtrl.$parsers.length = 0;
        }
    };
});

디렉티브를 사용하는 또 다른 간단한 방법:

HTML:

<input date-input type="time" ng-model="created_time">

지시:

app.directive('dateInput', function(){
    return {
        restrict : 'A',
        scope : {
            ngModel : '='
        },
        link: function (scope) {
            if (scope.ngModel) scope.ngModel = new Date(scope.ngModel);
        }
    }
});

이 에러로부터 회피할 수 있는 것은, 이 코드 조각입니다.이 코드는 실제로 날짜 형식의 에러입니다.일부 함수나 API에 우리의 날짜를 전달할 때 발생합니다.

            var options = {
                weekday: "long", year: "numeric", month: "short",
                day: "numeric", hour: "2-digit", minute: "2-digit"
            };
            $scope.campaign.date_start = $scope.campaign.date_start.toLocaleTimeString("en-us", options);

여기서 en-us format = 2013년 2월 1일 금요일 오전 6:00 이것이 다른 사람들의 문제 해결에 도움이 되기를 희망합니다.저는 이러한 에러에 직면하여 이 에러로 해결했습니다.

언급URL : https://stackoverflow.com/questions/26782917/model-is-not-a-date-object-on-input-in-angularjs

반응형