Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating common controller functions

How do I create some sort of utils bundle that would be accessible from all my controllers?

I have this route code in my main module:

'use strict';  angular.module('lpConnect', []).     config(['$routeProvider', function($routeProvider) {     $routeProvider.         when('/home', {template: 'views/home.html', controller: HomeCtrl}).         when('/admin', {template: 'views/admin.html', controller: AdminCtrl}).         when('/connect', {template: 'views/fb_connect.html', controller: MainAppCtrl}).         otherwise({redirectTo: '/connect'}); }]); 

I want a function that can be common to HomeCtrl, AdminCtrl and MainAppCtrl.

How should I do it in AngularJS?

like image 958
Shlomi Schwartz Avatar asked Jul 04 '12 07:07

Shlomi Schwartz


People also ask

What is controller in JavaScript?

A controller is a function you write to control your data. With a self-written controller, you can modify data anyway you want: Convert to upper case. Convert currencies. Calculate and Summarize.

What does controller do in angular?

The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object. You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements.


2 Answers

The way to define common code in angular is through Services.

You would define a new service like so :

.factory('CommonCode', function ($window) {         var root = {};         root.show = function(msg){             $window.alert(msg);         };         return root;     }); 

In your controller you would inject this service..like so

function MainAppCtrl($scope,CommonCode) {      $scope.alerter = CommonCode;      $scope.alerter.show("Hello World"); } 

Just include CommonCode as an argument to your controller function.. Angular will take care of injecting it for you ( Read on Dependancy Injection ..to understand what is happening here. )

like image 88
ganaraj Avatar answered Oct 18 '22 04:10

ganaraj


Just to update previous answer (which only define what factory is), there are 3 ways to inject dependencies (define common code) in AngularJS:

  • Providers
  • Factories
  • Services

I will not talk much about provider because it is a more laborious method for dependency injection. However, this page explains very well how they work.


Technically, service and factory are used for the same thing. It turns out, a service is a constructor function whereas a factory is not.

From this post:

module.service( 'serviceName', function ); 

When declaring serviceName as an injectable argument you will be provided with an instance of the function.

module.factory( 'factoryName', function ); 

When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.


You can use the one you prefer and obtain the same result.

Here is two codes doing exactly the same thing through service first, and then factory:

Service syntax

app.service('MyService', function () {   this.sayHello = function () {     console.log('hello');   }; }); 

Factory syntax

app.factory('MyService', function () {   return {     sayHello: function () {       console.log('hello');     }   } }); 
like image 36
Mistalis Avatar answered Oct 18 '22 04:10

Mistalis