angularjs - 对多个元素使用相同的指令

标签 angularjs angularjs-directive

我正在尝试遵循 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/

相关文章:

javascript - Angular 动态绑定(bind)指令范围

javascript - 刷新 AngularJS 中的 map

javascript - Angular 绑定(bind)不会更新

javascript - 从包含 ng-grid 对象的状态转换不起作用

javascript - Angular 同步相同的指令?

angularjs - 具有过滤器依赖性的测试指令

javascript - 在范围对象中定义但不可访问的属性

javascript - 带有发布/订阅的指令之间的 Angularjs 事件通信

rest - 使用 javascript(框架)使用 hatoas Restful 网络服务

angularjs - 页面加载时调用 Ionic 无限滚动函数