Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get the calendar object with AngularJS ui-calendar using the "controller as" syntax?

I am using ui-calendar from angular-ui. It's very nice and easy to use.

However, I am unable to get a hold of calendar object to call fullCalendar() and execute certain functions on the calendar.

The documentation only gives examples using the $scope approach, but I am using the controller as vm approach recommended by John Papa and others. I have tried using it this way:

<div data-ng-controller="races as vm">
    <div ui-calendar="vm.calendarConfig" calendar="vm.calendar"></div>
</div>

in the races controller I have the following:

vm = this;
vm.calendarConfig = { header: {...} };
vm.calendar = {};

// somewhere else in a separate click event
vm.calendar.fullCalendar('prev');    // ---> exception

That last line throws an exception Object has no method 'fullCalendar'.

Just wondering what I am missing and if anyone had an example of using ui-calendar with a controller as vm syntax.

Here is the plunker: http://plnkr.co/edit/DPo9meJHx19bREYFLhDh

like image 582
Eric Liprandi Avatar asked Oct 20 '22 12:10

Eric Liprandi


2 Answers

Thanks Josh Kurz for your help. Here is what I ended up doing: I used a hybrid of the $scope and controller as approach. Basically, I added a dependency on $scope to my controller. When I need access to the actual calendar control, I use $scope.calendar.fullCalendar('...'). The plunker has been updated, but here is core of it in the script file:

angular.module('app').controller(controllerId, ['$scope', races];
function races($scope) {
    var vm = this;
    ...
    function next() {
        $scope.calendar.fullCalendar('next');
    }
}

and in the html:

...
<div ui-calendar ng-model="vm.eventSources" calendar="calendar"></div>
...

Not as clean as I would like it, but it still seems clean enough for my purpose.

like image 99
Eric Liprandi Avatar answered Oct 23 '22 03:10

Eric Liprandi


Interesting question.

To accomplish this with your exact syntax I had to hack the uiCalendar. I added one condition that checks for a controller-as attribute on the directive. http://plnkr.co/edit/6Jj0UHD7A8a1v8SRZrYP?p=preview

<div ui-calendar ng-model="vm.eventSources" controller-as="vm" calendar="calendar"></div>


if(attrs.controllerAs){
  scope.calendar = scope.$parent.$eval(attrs.controllerAs)[attrs.calendar] =  elm.html('');
} else {
  scope.calendar = scope.$parent[attrs.calendar] =  elm.html('');
}

Not the prettiest solution, but it works. Not tested either, so use at your own discretion...

I think this could be a valid PR for the calendar if more people find it useful, but this is the first request I have heard of this type.

like image 27
joshkurz Avatar answered Oct 23 '22 02:10

joshkurz