0

我想使用 jqueryUi 和 angularjs 创建一个日期选择器。我想从我的所有控制器中获取 datepicker 值。为此,我创建了一个工厂:

App.factory "selectedDate", ['$rootScope', ($rootScope) ->
  selectedDates = {}
  selectedDates.from = moment()

  selectedDates.nextPeriod = ->
    this.from.add('days', 1);

  selectedDates.previousPeriod = ->
    this.from.subtract('days', 1);

  return selectedDates
]

我的控制器:

App.controller "DashboardDatePickerCtrl", ['$scope', 'selectedDate', ($scope,selectedDate) ->

  $scope.nextPeriod = () ->
    selectedDate.nextPeriod()

  $scope.previousPeriod = () ->
    selectedDate.previousPeriod()

  $scope.date = selectedDate.from
]

App.controller "otherCtrl", ['$scope', 'selectedDate', ($scope,selectedDate) ->
  $scope.date = selectedDate.from
]

我的 html (haml) :

.row-fluid{ "ng-controller" => "DashboardDatePickerCtrl" }
  .span4.offset5
    %span.fui-arrow-left.right10.top5.font-large.pointer{ "ng-click" => "previousPeriod()"}
    .control-group.inline
      .input-prepend.input-datepicker
        %button.btn{:type => "button"}
          %span.fui-calendar
        %input#datepicker-01.span2{:type => "text", "ng-model" =>"date", "datepicker" => ""}

    {{ date }}

    %span.fui-arrow-right.left10.font-large.pointer{ "ng-click" => "nextPeriod()"}

  .span3
    .btn-group.choose-granularity{"data-toggle" => "buttons-radio"}
      %button#by_4h.btn.btn-primary.one_month One month
      %button#by_1h.btn.btn-primary.one_week One week
      %button#by_5m.btn.btn-primary.one_day.active One day

.row-fluid
  .span12{ "ng-controller" => "otherCtrl" }
    %h6 An other ng controller
    %p
      {{ date.format("DD MMM, YYYY") }}

最后,我的 datepicker 指令:

App.directive('datepicker', (selectedDate) ->
  return {
    restrict: 'A'
    require : 'ngModel'
    link : (scope, element, attrs, ngModelCtrl) ->
      $ ->
        element.datepicker({
          showOtherMonths: true
          selectOtherMonths: true
          dateFormat: "d MM, yy"
          yearRange: '-1:+1'
          onSelect: (date) ->
            selectedDate.from = moment(date)
            scope.$apply();
        })
    }
);

事实是,当我在我的日期选择器中选择一个日期时,“otherCtrl”或“DashboardDatePickerCtrl”上的日期不会改变。

我认为更新我工厂的属性值将更新指向该变量的所有其他变量。

我错过了什么?

JSFIDDLE:http: //jsfiddle.net/9HZdm/6/

4

1 回答 1

2

问题是您丢失了对该.from属性的引用。一旦你的otherControllerandDashboardDatePickerCtrl开始,他们就会得到对selectedDate.from. 但是在您的日期更改处理程序中,您将 更改为.from内存中的另一个对象 ( selectedDate.from = ...),但控制器仍然指向旧的对象,现在永远丢失在内存中(非常戏剧性)。

修复它的简单方法是在控制器中公开整个 selectedDate,并绑定到它的子属性。这样,您将更改.from,但不会更改.selectedDate.

在您的控制器中,您应该使用$scope.date = selectedDate;而不是$scope.date = selectedDate.**from**在您的绑定中,您应该使用date.from.format(...). 这将解决问题。

如果您介意建议,还有UI-Bootstrap 日历指令

我在这个答案中谈了一点。

于 2013-07-11T13:37:54.857 回答