8

私は日付フォーマットに関するこのスタックオーバーフローの議論の例に従おうとしています.1つのページに1つの日付フィールドしかない場合は非常にうまく機能します. ただし、ページに複数の日付フィールドがある場合、他の日付フィールドが選択されていても、最初の日付フィールド/ng-model のみが設定されるようです。

以下は、HTML テンプレート コードです。

    <div class="input-append" my-Datepickerloaded>
        <input type="text" ng-model="user.StartDate" my-Datepickerformater></input>
        <span class="add-on">
            <i data-time-icon="icon-time" data-date-icon="icon-calendar">
            </i>
        </span>
    </div>


    <div class="input-append" my-Datepickerloaded>
        <input type="text" ng-model="user.EndDate" my-Datepickerformater></input>
        <span class="add-on">
            <i data-time-icon="icon-time" data-date-icon="icon-calendar">
            </i>
        </span>
    </div>

そして、ディレクティブ コード ( myDatePickerformater ) は次のとおりです。

return {
            require: '^ngModel',
            restrict: 'A',
            link: function (scope, elm, attrs, ctrl) {
                var moment = $window.moment,
                    dateFormat = 'MM/DD/YYYY';

                attrs.$observe('myDatepickerformater', function (newValue) {
                    ctrl.$modelValue = new Date(ctrl.$setViewValue);
                });

                ctrl.$formatters.unshift(function (modelValue) {
                    scope = scope;
                    if (!dateFormat || !modelValue) return '';
                    var retVal = moment(modelValue).format(dateFormat);
                    return retVal;
                });

                ctrl.$parsers.unshift(function (viewValue) {
                    scope = scope;
                    var date = moment(viewValue, dateFormat);
                    return (date && date.isValid() && date.year() > 1950) ? date.toDate() : "";
                });
            }
        };

バインド先のモデルで $scope.$watch を実行しようとしましたが、user.EndDate入力フィールドを変更している場合でも、常にuser.StartDateが変更を取得し、user.EndDateが変更されていないようです。 「入力」フィールドが両方のフィールドを正しく表示している場合。

両方のフィールドのバインド モデルが正しく更新されるようにするにはどうすればよいですか?

助けてくれてありがとう。

4

1 に答える 1

6

ディレクティブにisolated scope.

現在、ディレクティブの複数のインスタンスが同じスコープを共有しているため、モデルの更新が期待どおりに機能していません。

docs.angularjs.org/guide/directiveを見てください。

require: '^ngModel',
restrict: 'A',
scope: {
    ...
},
link: function (scope, elm, attrs, ctrl) {
    ....
于 2014-07-07T21:50:22.273 に答える