我正在尝试遵循 this stackoverflow discussion on date formatting 中的示例,它适用于只有一个日期字段的页面。但是,如果页面上有多个日期字段,则似乎只有 第一个日期字段/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() : "";
});
}
};
我试图在他们绑定(bind)的模型上做一个 $scope.$watch,看起来即使我正在更改 user.EndDate 输入字段,始终为 user.StartDate 得到零钱和 user.EndDate 即使“输入”字段正确显示两个字段,也保持不变。
如何确保两个字段都能正确更新其绑定(bind)模型?
谢谢你的帮忙。
最佳答案
你需要给你的指令一个 isolated scope
.
目前,该指令的多个实例共享相同的范围,因此更新模型无法按预期工作。
看看docs.angularjs.org/guide/directive
require: '^ngModel',
restrict: 'A',
scope: {
...
},
link: function (scope, elm, attrs, ctrl) {
....
关于angularjs - 对多个元素使用相同的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17605523/