Reputation: 123
I'm using angular strap datepicker and I want to execute some of my own logic when the datepicker opens up and closes.
How can I recognize these events inside my controller, and bind to them?
and not just to the datepicker events, but any of angular straps events for that matter.
An example of what I want to do:
http://plnkr.co/edit/Uy1Lz6I0NWSACV4kyljk?p=catalogue
Upvotes: 2
Views: 2903
Reputation: 1032
Let's say you want to get the selected date in your controller and do something with it:
Add this to your controller:
$rootScope.$watch('datepickerDateSelected', function(date){
// do whatever you want with the date parameter here
});
And modify the datepicker directive $scope.select method, like this:
scope.$select = function (date) {
$rootScope.datepickerDateSelected = date; // ADD THIS
$datepicker.select(date);
};
[ UPDATE ]
Using $broadcast/$on. Modify the directive ($datepicker.show and $datepicker.hide methods) like this:
$datepicker.show = function(){
...
$rootScope.$broadcast('opening'); // ADD THIS
...
}
$datepicker.hide= function(blur){
...
$rootScope.$broadcast('closing'); // ADD THIS
...
}
And in your controller, add this (you don't need to $watch anything):
$rootScope.$on('opening', function(event, data) { console.log("it's opening!"); });
$rootScope.$on('closing', function(event, data) { console.log("it's closing!"); });
It worked in my case, but you may want to check this: Working with $scope.$emit and $scope.$on (see answer from zbynour)
If you don't want to use $broadcast/$on (see the comments), just use $watch like in the first example instead.
Upvotes: 3
Reputation: 1676
I checked the code for AngularStrap's datepicker. They provide a $datepicker
service which I thought could be decorated to achieve what you wanted, but this should be done in the config
phase of your app, and the service would require a DOM element to be initialized. Thus, I think this solution is not feasible.
Anyway, I looked at Angular-UI's datepicker, and it provides attributed to specify functions to use for the open
and close
events. It would be much easier to use those and emit your events there.
Upvotes: 0