Xgongiveittoya
Xgongiveittoya

Reputation: 753

Where should I put these function and variables currently in my Angularjs Controller

I have a single page app that displays a table that is editable by the user. There is a date-picker that I use that requires some properties and functions to be set.

Those are currently sitting in my controller, which is becoming very bloated. ~380 lines, ~130 of which are date-picker code.

I could put them in a factory, and use them through that, but I am not sure if that would work, as many of these properties and functions are sitting in the controllers scope.

Any suggestions would be helpful!

The date-picker I am using is: Here

I have moved the .directive to its own file already.

Upvotes: 0

Views: 26

Answers (1)

Abdul Ahmad
Abdul Ahmad

Reputation: 10021

yes, you can put it in a factory or service. all you have to do is create the service, put the code in there, and inject the service into your controller. then you will be able to access the service from your controller:

i'm not sure what angular syntax you're using but here's a sample:

angular.module('app', [])
.service('datepicker', datepicker)
.controller('controller', controller);

function datepicker() {
 //codes
}

controller.$inject = ['datepicker'];
function controller(datepicker) {
 //codes
 datepicker.function(); //call some datepicker service function
}

if you want to access service functions from the view you need to do the following:

controller.$inject = ['datepicker'];
function controller(datepicker) {
 //codes
 self.datepicker = datepicker;
 datepicker.function(); //call some datepicker service function
}

then in the view you do:

<div ng-controller='controller as ctl'>
 {{ctl.datepicker.function()}}
</div>

Upvotes: 1

Related Questions