我想使用 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/